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?
Static methods are called
static
because they can be invoked without instantiating class object. So, you cannot passstatic class
(evenstatic class
is not a legal term).Available options are:
Pass object of
Carbon:now()
to your constructor:Pass a callable object:
And later create
Carbon
instance using something like:Using second option you can define function name dynamically.