Laravel Provider用法

创建

php artisan make:provider NoticationServiceProvider

注册服务提供者
将该类追加到配置文件config/app.php的providers数组中

'providers' => [
    //其他服务提供者
    App\Providers\TestServiceProvider::class,
],

两种方式
第一,通过绑定服务ID的方式定义的服务,只能通过服务ID来获取
// 定义服务

class NotificationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('service_id', function () {
            return new Service();
        })
    }
}

// 获取服务,以下方式等价 controller

public function store()
{
    app('service_id')
}

第二,你想通过接口的类型提示(Type Hint)来自动解析并注入服务

public function register()
{
    // 绑定接口到实例
    $this->app->bind('Namespace\To\Your\Interface\Pay', 'Namespace\To\Your\Class\Weixin');
}

第三,像上边这样,通过绑定接口到实例,只能自动解析为一个实例,也就是你绑定的实例;如果你想要的结果是,不同的类,构造器通过类型提示(Type Hint)相同的接口,注入不同的实例,可以像下边这样(上下文绑定,Context Binding)

public function register()
{
    $this->app->when('Namespace\To\Your\Class\A')
          ->needs('Namespace\To\Your\Interface\Pay')
          ->give('Namespace\To\Your\Class\Weixin');
          
    $this->app->when('Namespace\To\Your\Class\B')
          ->needs('Namespace\To\Your\Interface\Pay')
          ->give('Namespace\To\Your\Class\Ali');
}

通过上下文绑定,A的实例会注入Weixin的实例,而B的实例会注入Ali的实例。像下边:

class A
{
    public functions __construct(Pay $pay)
    {
        var_dump($pay instanceof Weixin); // True
    }
}

class B
{
    public functions __construct(Pay $pay)
    {
        var_dump($pay instanceof Ali); // True
    }
}

----------------------------------------------------------------------------------------------------------

1.绑定一个class,调用的时候直接实例化这个class

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

class NotificationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('notification.forUser', 'App\Library\Services\NotificationForUser');
    }
}

NotificationServiceInterface.php
namespace App\Library\Services\Contracts;
  
Interface NotificationServiceInterface
{
    public function printNotice();
}


Notification.php
namespace App\Library\Services;

use App\Library\Services\Contracts\NotificationServiceInterface;

class NotificationForUser implements NotificationServiceInterface
{
    public function printNotice()
    {
      return 'Welcome ' . auth()->user()->name . ' !';
    }
}


public function store()
{
    if (!auth()->attempt(request(['name', 'password']))) {
        return back()->withErrors([
            'message' => "Please check your credientials and try again."
        ]);
    }

    // Get notice from session('notice') in template.
    return redirect()->home()->with('notice' , app('notification.forUser')->printNotice());
}

2.绑定一个接口,调用的时候直接实例化这个接口
需要在调用的类中注入接口才会生效

namespace App\Providers;
use Illuminate\Support\ServiceProvider;

class NotificationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Library\Services\Contracts\NotificationServiceInterface',
            function ($app) {
                return new \App\Library\Services\NotificationForUser();
        });
    }
}

use App\Library\Services\Contracts\NotificationServiceInterface;
...
public function store(NotificationServiceInterface $NotificationForUserInstance)
{
    if (!auth()->attempt(request(['name', 'password']))) {
        return back()->withErrors([
            'message' => "Please check your credientials and try again."
        ]);
    }

    // Get notice from session('notice') in template.
    return redirect()->home()->with('notice' , $NotificationForUserInstance->printNotice());
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值