Passing Static Classes Through Injection Dependancy

How can I pass a static class to an object through Injection Dependency?

For example, Carbon uses static methods:

$tomorrow = Carbon::now()->addDay();

I have services that depend on Carbon, and currently I use the library in dependencies without inserting them. But this increases the connection, and I would like to pass it through DI instead.

I have the following controller:

$container['App\Controllers\GroupController'] = function($ci) {
    return new App\Controllers\GroupController(
        $ci->Logger,
        $ci->GroupService,
        $ci->JWT
    );
};

How to pass Carbon into this?

+4
source share
1 answer

static, , . , static class ( static class ).

:

  • Carbon:now() :

    $container['App\Controllers\GroupController'] = function($ci) {
        return new App\Controllers\GroupController(
            $ci->Logger,
            $ci->GroupService,
            $ci->JWT,
            \Carbon:now()          // here
        );
    };
    
  • :

    $container['App\Controllers\GroupController'] = function($ci) {
        return new App\Controllers\GroupController(
            $ci->Logger,
            $ci->GroupService,
            $ci->JWT,
            ['\Carbon', 'now']   // here or '\Carbon::now'
        );
    };
    

    Carbon, - :

    $carb_obj = call_user_func(['\Carbon', 'now']);
    $carb_obj = call_user_func('\Carbon::now');
    

, .

0

Source: https://habr.com/ru/post/1663952/


All Articles