![](/img/trans.png)
[英]How to properly remove a table from folder migration in laravel? (With artisan command)
[英]How to properly inject dependency into Laravel artisan command?
基本上我想从laravel命令调用存储库Repository.php上的方法。
Example\Storage\Repository.php
Example\Storage\RepositoryInerface.php
Example\Storage\RepositoryServiceProvider.php
我希望在命令构造函数中使用Interface,然后将其设置为受保护的变量。
在服务提供者中,我将Interface绑定到Repository类。
现在,在start / artisan.php中我写道:
Artisan::add(new ExampleCommand(new Repository());
我可以在这里使用界面吗? 什么是正确的方法? 我很迷惑。
提前致谢。
编辑:澄清一下,它只能按现在的方式工作,但我不想在注册artisan命令时硬编码具体类。
您可以使用IoC容器的自动依赖注入功能:
Artisan::add(App::make('\Example\Commands\ExampleCommand'));
// or
Artisan::resolve('\Example\Commands\ExampleCommand');
如果ExampleCommand的构造函数接受一个具体类作为其参数,那么它将自动注入。 如果它依赖于接口,则需要告诉IoC容器在请求给定接口时使用特定的具体类。
具体(为简洁而忽略名称空间):
class ExampleCommand ... {
public function __construct(Repository $repo) {
}
}
Artisan::resolve('ExampleCommand');
接口(为简洁而忽略名称空间):
class ExampleCommand ... {
public function __construct(RepositoryInterface $repo) {
}
}
App::instance('RepositoryInterface', new Repository);
Artisan::resolve('ExampleCommand');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.