[英]How to use custom Service Providers in Laravel 5.2
I am creating a Laravel app that needs to communicate with a remote (in-house) service via API. 我正在创建一个Laravel应用,该应用需要通过API与远程(内部)服务进行通信。
This API needs to be authenticated at least once per session, and after that other calls can work fine. 每个会话至少需要对该API进行一次身份验证,然后再进行其他调用即可。
I think the best way is to use Laravel's service providers to do this, but I'm open to other solutions. 我认为最好的方法是使用Laravel的服务提供商来执行此操作,但是我对其他解决方案持开放态度。
What I would like is a way to have this Service available for use whenever. 我想要的是一种可以随时使用此服务的方法。 I don't want to have to put the service in the parameters of a controller's method if I can avoid it. 如果可以避免的话,我不想将服务放在控制器方法的参数中。 Something like this: 像这样:
use MyServiceProvider;
class SomeController extends Controller
{
public function someMethod ()
{
MyServiceProvider::method();
}
}
I can post what I've started doing thus far, if needed - but I'd rather focus on doing what I want rather than fixing what I did wrong . 如果需要的话,我可以发布到目前为止我已经开始做的事情-但我宁愿专注于做自己想做的事情,而不是解决自己做错的事情 。
inb4: I did read the docs. inb4:我确实阅读了文档。
What you're trying to do is create a Facade. 您想要做的就是创建一个Facade。 Facades are very similar to using dependency injection, except that they can be used globally without specific injection. 外墙与使用依赖项注入非常相似,不同之处在于它们可以在不进行特定注入的情况下全局使用。 Docs: https://laravel.com/docs/5.0/facades#creating-facades 文件: https : //laravel.com/docs/5.0/facades#creating-facades
In your service provider: 在您的服务提供商中:
App::bind('foo', function()
{
return new \MyServices\Foo; //returns a concrete class
});
Foo.php Foo.php
use Illuminate\Support\Facades\Facade;
class Foo extends Facade {
protected static function getFacadeAccessor() { return 'foo'; } //matches binding in SP
}
Now your service provider is available as Foo
anywhere, even without explicitly injecting it: 现在,即使没有明确注入,您的服务提供商也可以在任何地方以Foo
形式使用:
use Foo;
class SomeController extends Controller
{
public function someMethod ()
{
Foo::method(); //creates a Foo object according to App::bind, then calls method();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.