9

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?

BugHunterUK
  • 8,346
  • 16
  • 65
  • 121

1 Answers1

3

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.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • Why is `static class` not a legal term? I think I'll have to continue to import Carbon directly into my services because I don't always need to use `Carbon::now`. At times I need to use `Carbon::createFromTimestamp`. Thanks anyway, will accept because this pretty much answers the question. – BugHunterUK Dec 16 '16 at 13:35
  • `static class` is not a legal term, because there can be static properties or static methods. Even if your class has only static props/methods you still can create an instance of it (though you will not have many options how to use it) – u_mulder Dec 16 '16 at 13:44
  • Ah I see what you mean, PHP has no definition of a static class like in other languages such as C#. Although setting the constructor to a private method would stop the class being instantiated. Or creating an abstract class consisting of only static properties and methods. Thanks again. – BugHunterUK Dec 16 '16 at 14:01