php - 流明中的依赖注入
问题描述
我试图了解流明中的依赖注入
我想添加用户服务
{
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 ]]
解决方案
可以在服务提供者中配置带参数的依赖关系。可以通过运行以下命令生成服务提供者:
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;
}
推荐阅读
- python - 如何找到列表中键最多的字典?
- docusignapi - 检查 HMAC 签名
- c# - 使用带有 sql 查询的文本框过滤 WPF C# DataGrid
- kubernetes - 在 Operator-SDK 中,多个 Patch 在一个协调功能中
- jquery - Moodle 测验仅在尝试期间而不是在复习期间显示模式
- java - 为什么 SonarQube 添加“没有足够的论点”。对于带有消息和 Throwable 的日志方法?
- android - 使用 Koin 进行适当的仪器测试
- python-3.x - 如何使用 elasticsearch-dsl-py 加入两个 ElasticSearch 索引?
- windows - 无法在 windows server 2019 节点上创建 kubernetes pod
- core-data - 如何在 coreData 的谓词中使用 AppStorage