首页 / PHP / php-Laravel服务提供商说明
php-Laravel服务提供商说明
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php-Laravel服务提供商说明,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2680字,纯文字阅读大概需要4分钟。
内容图文
我对Laravel Service provider不太熟悉,对此有疑问.
示例:我有三个类SystemProfiler,SurveyProfiler和OfferProfiler,它们实现了ProfilerInterface.而且我还有ProfilerService类,该类将ProfilerInterface注入构造函数中.我需要通过注入每个探查器来创建不同的探查器服务.
ProfilerService:
class ProfilerService {
$this->profiler;
function __construct(ProfilerInterface $profiler) {
$this->profiler = profiler;
}
}
我知道如何在symfony2框架中做到这一点:
system_profiler:
class: App\MyBundle\Profiles\SystemProfiler
survey_profiler:
class: App\MyBundle\Profiles\SurveyProfiler
offer_profiler:
class: App\MyBundle\Profiles\OfferProfiler
system_profile_service:
class: App\MyBundle\Services\ProfilerService
arguments:
- system_profiler
survey_profile_service:
class: App\MyBundle\Services\ProfilerService
arguments:
- survey_profiler
offer_profile_service:
class: App\MyBundle\Services\ProfilerService
arguments:
- offer_profiler
然后只需使用ProfilerService实现的别名调用$this-> container-> get()
但是Laravel文档说:“如果类不依赖于任何接口,则无需将类绑定到容器中.”而且ProfilerService不依赖于接口.因此,我可以将每个事件探查器绑定到接口,如下所示:
$this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\SystemProfiler');
要么
$this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\SurveyProfiler');
要么
$this->app->bind('App\MyBundle\Contracts\ProfilerInterface','App\MyBundle\Profiles\OfferProfiler');
但是我应该如何绑定哪些探查器应该注入探查器服务以及何时?
我将不胜感激任何帮助和解释
解决方法:
它去了(read the docs):
// ServiceProvider
public function register()
{
// Simple binding
$this->app->bind('some_service.one', \App\ImplOne::class);
$this->app->bind('some_service.two', \App\ImplTwo::class);
// Aliasing interface - container will inject some_service.one
// whenever interface is required...
$this->app->alias('some_service.one', \App\SomeInterface::class);
// ...except for the Contextual Binding:
$this->app->when(\App\DependantTwo::class)
->needs(\App\SomeInterface::class)
->give('some_service.two');
}
用法:
$php artisan tinker
// Aliases
>>> app('some_service.one')
=> App\ImplOne {#669}
>>> app('some_service.two')
=> App\ImplTwo {#671}
// Aliased interface
>>> app('App\SomeInterface')
=> App\ImplOne {#677}
>>> app('App\DependantOne')->dependency
=> App\ImplOne {#677}
// Contextual
>>> app('App\DependantTwo')->dependency
=> App\ImplOne {#676}
鉴于此设置:
namespace App;
class ImplOne implements SomeInterface {}
class ImplTwo implements SomeInterface {}
class DependantOne
{
public function __construct(SomeInterface $dependency)
{
$this->dependency = $dependency;
}
}
class DependantTwo
{
public function __construct(SomeInterface $dependency)
{
$this->dependency = $dependency;
}
}
内容总结
以上是互联网集市为您收集整理的php-Laravel服务提供商说明全部内容,希望文章能够帮你解决php-Laravel服务提供商说明所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。