The example in this article describes how to create service provider and facade in laravel5. Share it with everyone for your reference, the details are as follows:
laravel5 creates a facade, which can register a service as a facade, so that you don’t need to bother using it. The article uses an example to illustrate how to create service provider and facade.我 Target
I hope I can create a Facade of AjaxResponse so that I can use it directly in Controller:
class MechanicController extends Controller { public function getIndex() { \AjaxResponse::success(); } }
its role is to regulate the format returned as
{ code: "0" result: { } }
Create
Creation
Service class
Create a class
<?php namespace App\Services; class AjaxResponse { protected function ajaxResponse($code, $message, $data = null) { $out = [ 'code' => $code, 'message' => $message, ]; if ($data !== null) { $out['result'] = $data; } return response()->json($out); } public function success($data = null) { $code = ResultCode::Success; return $this->ajaxResponse(0, '', $data); } public function fail($message, $extra = []) { return $this->ajaxResponse(1, $message, $extra); } }
in the app/Services folder
This AjaxResponse is a specific implementation class. Next we have to make a provider for this class
Create a provider
in the app/Providers folder Create class
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class AjaxResponseServiceProvider extends ServiceProvider { public function register() { $this->app->singleton('AjaxResponseService', function () { return new \App\Services\AjaxResponse(); }); } }
Here we defined the Service name as AjaxResponseService when registering
Next we define a facade
Create facade
Create class
<?php namespace App\Facades; use Illuminate\Support\Facades\Facade; class AjaxResponseFacade extends Facade { protected static function getFacadeAccessor() { return 'AjaxResponseService'; } }
in the app/Facades folder
Modify the configuration file
Okay, now we only need to mount these two things in app.php
<?php return [ ... 'providers' => [ ... 'App\Providers\RouteServiceProvider', 'App\Providers\AjaxResponseServiceProvider', ], 'aliases' => [ ... 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AjaxResponse' => 'App\Facades\AjaxResponseFacade', ], ];
Summary
It is relatively easy to use the facade in laravel5, Basically no difference from 4.
🎜I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework. 🎜🎜For more detailed explanations of how to create service providers and facades in laravel5, please pay attention to the PHP Chinese website! 🎜