Search code examples
phpdependency-injectionlumen

dependency injection in lumen


I'm trying to understand dependency injection in lumen

I want to add userService

{
    protected $userService;
    public function __construct(UserService $userService, $config)
    {
        $this->userService = $userService;
    }

apply it here: Console/Commands/Command2.php

    $server = app(Server::class, [$config]);

getting an error

In Container.php line 993: Unresolvable dependency resolving [Parameter #1 [ $config ]] in class App\SocketServer\Server


Solution

  • Dependencies with parameters can be configured in service providers. A service provider can be generated by running:

    php artisan make:provider UserServiceProvider
    

    Modifying the setup method in the UserServiceProvider.php file

        public function register()
        {
            $this->app->singleton(UserService::class, function ($app) {
                $config = ['debug' => true];
                return new UserService($config);
            });
        }
    

    registering it in config/app.php:

    'providers' => [
        // Other Service Providers
    
        App\Providers\UserServiceProvider::class,
    ],
    

    And then Laravel will be able to inject the dependency:

        protected $userService;
        public function __construct(UserService $userService)
        {
            $this->userService = $userService;
        }