LARAVEL5 Create a facade, you can register a service with a façade, so that you do not need to use the trouble when using. This article uses an example to illustrate how to create service provider and facade.
Goal
I want me to create a ajaxresponse facade so that I can use it directly in the controller:
Class Mechaniccontroller extends Controller {public function GetIndex () { \ajaxresponse::success ()} }
Its function is that the canonical return format is
{ code: ' 0 ' result: { }}
Steps
Create service class
To create a class in the App/services folder
$code, ' message ' and $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); }}
This ajaxresponse is a concrete implementation class, so let's do a provider for this class.
Create Provider
To create a class in the App/providers folder
App->singleton (' Ajaxresponseservice ', function () { return new \app\services\ajaxresponse () });} }
Here we define this service name as Ajaxresponseservice in register.
Here we define a backyards facade
Create facade
To create a class in the App/facades folder
!--? php namespace App\facades;use illuminate\support\facades\facade;class Ajaxresponsefacade Extends facade {protected static function Getfacadeaccessor () {return ' Ajaxresponseservice ';}} Modifying a configuration file
OK, now we just need to go to the app.php to mount the two things on it.
!--? Phpreturn [... ' Providers ' =--> [... ' App\providers\routeserviceprovider ', ' App\providers\ajaxresponseserviceprovider ',], ' aliases ' = [ ... ' Validator ' = ' illuminate\support\facades\validator ', ' View ' = ' Illuminate\support\facades\view ', ' Ajaxresponse ' = ' app\facades\ajaxresponsefacade ',],];
It is easy to summarize the use of facade in the Laravel5, and the basic and 4 are no different.