laravel 服务提供者 facade初使用及理解

时间:2020-12-25 16:13:20

使用服务提供者注册服务进行依赖注入后可以直接Class::method()调用否则得自己new一个实例

<?php


namespace App\Providers;


use Illuminate\Support\ServiceProvider;


class MyViewComposer extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }


    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('myviewcomposera',function(){
            //return new TestService();
            return new \App\Http\ViewComposers\MyViewComposer;
        });


        $this->app->bind('App\Contracts\ComposerContract', function() //两种绑定方式
        {
            return new \App\Http\ViewComposers\MyViewComposer;
        });
    }
}
facade其实就是创建一个静态类

<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;

class MyViewComposer extends Facade {

protected static function getFacadeAccessor() { return 'myviewcomposera'; }

}
config文件夹app.php中注册别名
 'MyViewComposer' => App\Facades\MyViewComposer::class,
创建契约接口方便后面依赖注入
<?php


namespace App\Contracts;
use Illuminate\Contracts\View\View;


interface ComposerContract
{
    public function compose(View $view);
    public function setnavbar($data);  
}
创建类

<?php namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use App\Contracts\ComposerContract;
use Cache;
use Carbon\Carbon;
class MyViewComposer implements ComposerContract
{
public function compose(View $view)
{
$view->with('sitename',Cache::get('navbar',[1,0,0,0]));
}
public function setnavbar($data){
Cache::put('navbar', $data, Carbon::now()->addSeconds(300));
}
}


使用
<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Role;
use App\Permission;
use App\Contracts\ComposerContract;
//use App\Facades\MyViewComposer; //使用全名
use MyViewComposer;//使用别名

class RoleController extends Controller
{
//自己进行依赖注入
public function __construct(ComposerContract $test){ //需要取消使用全名注释
$this->composer = $test;
}

public function welcome()
{
$users=Role::get();
foreach ($users as $user) {
$user->permissions;
}
// $this->composer->setnavbar([0,0,0,[1,0,0]]);
MyViewComposer::setnavbar([0,0,0,[1,0,0]]);
//Cache::put('navbar', [0,0,1,0], Carbon::now()->addSeconds(300));
return view('admin/role',['roledata'=>$users,'permissions'=>Permission::all()]);
}

}

facade就相当于帮你依赖注入了