我试图了解流明中的依赖注入
我要添加userService
{
protected $userService;
public function __construct(UserService $userService, $config)
{
$this->userService = $userService;
}
在此应用:控制台/命令/Command2.php
$server = app(Server::class, [$config]);
收到错误
在Container.php第993行中:无法解析依赖项,解析类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;
}