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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?