创建一个需要绑定到服务容器的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'));
}
}
浏览器访问
简单总结
- 1 创建一个需要绑定到服务容器的类
- 创建一个静态指向类的门面
- 创建服务提供者,并绑定类到服务容器
- 4 修改配置文件
日常开发一些框架共用的东西都可以用这种方法,例如系统间的service,上下文,辅助类等。