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 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题