Ren*_*Ren 12 php dependency-injection ioc-container laravel laravel-4
基本上我想从laravel命令调用存储库Repository.php上的方法.
Example\Storage\Repository.php
Example\Storage\RepositoryInerface.php
Example\Storage\RepositoryServiceProvider.php
Run Code Online (Sandbox Code Playgroud)
我希望在命令构造函数中使用Interface,然后将其设置为受保护的变量.
在服务提供者中,我将Interface绑定到Repository类.
现在,在start/artisan.php中我写道:
Artisan::add(new ExampleCommand(new Repository());
Run Code Online (Sandbox Code Playgroud)
我可以在这里使用界面吗?什么是正确的方法?我很迷惑.
提前致谢.
编辑:澄清一下,它只能按现在的方式工作,但我不想在注册artisan命令时硬编码具体类.
ale*_*ell 16
您可以使用IoC容器的自动依赖注入功能:
Artisan::add(App::make('\Example\Commands\ExampleCommand'));
// or
Artisan::resolve('\Example\Commands\ExampleCommand');
Run Code Online (Sandbox Code Playgroud)
如果ExampleCommand的构造函数接受一个具体类作为其参数,那么它将自动注入.如果它依赖于接口,则需要告诉IoC容器在请求给定接口时使用特定的具体类.
具体(为简洁而忽略名称空间):
class ExampleCommand ... {
public function __construct(Repository $repo) {
}
}
Artisan::resolve('ExampleCommand');
Run Code Online (Sandbox Code Playgroud)
接口(为简洁而忽略名称空间):
class ExampleCommand ... {
public function __construct(RepositoryInterface $repo) {
}
}
App::instance('RepositoryInterface', new Repository);
Artisan::resolve('ExampleCommand');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6359 次 |
| 最近记录: |