首页 > 解决方案 > 流明中的依赖注入

问题描述

我试图了解流明中的依赖注入

我想添加用户服务

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

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

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

收到错误

在 Container.php 第 993 行:类 App\SocketServer\Server 中无法解析的依赖解析 [Parameter #1 [ $config ]]

标签: phpdependency-injectionlumen

解决方案


可以在服务提供者中配置带参数的依赖关系。可以通过运行以下命令生成服务提供者:

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;
    }

推荐阅读