PHP笔记

laravel 自定义门面(facade/provider)

2019-03-12  本文已影响1人  零一间

创建一个需要绑定到服务容器的Jsonify类

<?php

namespace App\System;

use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;

class Jsonify
{
    use ValidatesRequests;

    private $_response = ['data'=> null, 'code'=> 0, 'message'=> ''];

    public function __construct(Application $app)
    {
        //
    }

    public function success($data=null, string $message='')
    {
        $response = $this->_response;

        $response['data'] = $data;
        $response['message'] = $message;

        return response()->json($response);
    }

    public function error(string $message, int $code=1)
    {
        $response = $this->_response;

        $response['message'] = $message;
        $response['code'] = $code;

        return response()->json($response);
    }

    public function validate(Request $request, array $rules)
    {
        $validator = $this->getValidationFactory()->make($request->all(), $rules);
        if ($validator->fails()) {
            abort(400, implode('', $validator->errors()->all()));
        }
    }
}

创建一个静态指向 Jsonify 类的门面类 Facade

继承 Illuminate\Support\Facades\Facade,实现getFacadeAccessor方法

<?php

namespace App\System\Facades;


use Illuminate\Support\Facades\Facade;

class Jsonify extends Facade
{

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

创建服务提供者,并绑定Jsonify类到服务容器

php artisan make:provider JsonifyServiceProvider

实现代码

<?php

namespace App\Providers;

use App\System\Jsonify;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        // 绑定Jsonify类到服务容器
        $this->app->singleton("Jsonify",function ($app){
            return new Jsonify();
        });
    }
}
 

修改配置文件 config/app.php

providers

App\Providers\JsonifyServiceProvider::class,

aliases

'Jsonify' => \App\System\Facades\Jsonify::class,

测试

添加路由

Route::get('/index','Controller@index');

测试代码

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function index(Request $request)
    {
        \Jsonify::validate($request, [
            'username' => 'required|string',
        ]);
        return \Jsonify::success($request->get('username'));
    }
}

浏览器访问

image.png

简单总结

日常开发一些框架共用的东西都可以用这种方法,例如系统间的service,上下文,辅助类等。

上一篇下一篇

猜你喜欢

热点阅读