流明中的依赖注入

dependency injection in lumen

我正在尝试了解 lumen 中的依赖注入

我要添加用户服务

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

在这里应用它: Console/Commands/Command2.php

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

出现错误

在 Container.php 第 993 行: class App\SocketServer\Server

中无法解析的依赖项解析 [Parameter #1 [ $config ]]

可以在服务提供者中配置带参数的依赖。可以通过 运行:

生成服务提供者
php artisan make:provider UserServiceProvider

修改UserServiceProvider.php文件中的设置方法

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

正在config/app.php注册:

'providers' => [
    // Other Service Providers

    App\Providers\UserServiceProvider::class,
],

然后Laravel就可以注入依赖了:

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