Dependency Injection Slim Framework 3

前端 未结 1 1234
无人共我
无人共我 2021-01-12 14:36

I\'m using Slim Framework 3 to create an API. The app structure is: MVCP (Model, View, Controller, Providers).

Is it possible to have Slim Dependency Inject

相关标签:
1条回答
  • 2021-01-12 14:57

    When you reference a class in the route callable Slim will ask the DIC for it. If the DIC doesn't have a registration for that class name, then it will instantiate the class itself, passing the container as the only argument to the class.

    Hence, to inject the correct dependencies for your controller, you just have to create your own DIC factory:

    $container = $app->getContainer();
    $container['\Controllers\PeopleController'] = function ($c) {
        $peopleService = $c->get('\Services\PeopleService');
        return new Controllers\PeopleController($c, $peopleService);
    };
    

    Of course, you now need a DIC factory for the PeopleService:

    $container['\Services\PeopleService'] = function ($c) {
        $peopleModel = new Models\PeopleModel;
        $addressModel = new Models\AddressModel;
        $autoModel = new Models\AutoModel;
        return new Services\PeopleService($peopleModel, $addressModel, $autoModel);
    };
    

    (If PeopleModel, AddressModel, or AutoModel had dependencies, then you would create DIC factories for those too.)

    0 讨论(0)
提交回复
热议问题