doukezi4606 2016-02-24 22:04
浏览 7
已采纳

如何在Laravel 5.2中使用自定义服务提供程序

I am creating a Laravel app that needs to communicate with a remote (in-house) service via API.

This API needs to be authenticated at least once per session, and after that other calls can work fine.

I think the best way is to use Laravel's service providers to do this, but I'm open to other solutions.

What I would like:

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.

  • 写回答

1条回答 默认 最新

  • doumei1908 2016-02-24 22:12
    关注

    What you're trying to do is create a 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

    In your service provider:

    App::bind('foo', function()
    {
        return new \MyServices\Foo; //returns a concrete class
    });
    

    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:

    use Foo;
    
    class SomeController extends Controller 
    {
        public function someMethod ()
        {
            Foo::method(); //creates a Foo object according to App::bind, then calls method();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘