Passing static classes via Dependancy Injection

2.4k views Asked by At

How is it possible to pass a static class to an object via Dependency Injection?

For example Carbon uses static methods:

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

I have services that depend on Carbon, and currently I'm using the library in the dependancies without injecting them. But, this increases coupling and I'd like to instead pass it in via DI.

I have the following controller:

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

How do I pass Carbon into that?

1

There are 1 answers

3
u_mulder On BEST ANSWER

Static methods are called static because they can be invoked without instantiating class object. So, you cannot pass static class (even static class is not a legal term).

Available options are:

  1. Pass object of Carbon:now() to your constructor:

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

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

    And later create Carbon instance using something like:

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

Using second option you can define function name dynamically.