简体   繁体   中英

Passing static classes via Dependancy Injection

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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM