Laravel Steps

Laravel Provider Register的用法

2018-11-01  本文已影响0人  AnnaJIAN

写一个登录成功之后自动打印欢迎消息的小例子

两种绑定的方法

php artisan make:provider NoticationServiceProvider

绑定一个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 . ' !';
    }
}

调用,登录之后printNotice

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());
}

Redirect 之后,参数只能通过session来传递了。
所以blade.php里面用session

@if (session('notice'))
    <div class="alert alert-success">
        {{ session('notice') }}
    </div>
@endif 

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

!!需要在调用的类中注入接口才会生效

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());
}

最后结果差不多这样,登录之后自动触发


Print Notice
上一篇 下一篇

猜你喜欢

热点阅读