How can laravel5 create serviceprovider and facade laravel5 to create a facade? you can register a service as a facade. in this way, you do not need to use it in any way. This article uses an example to illustrate how to create a service provider and a facade.
Target
I want to create an AjaxResponse facade so that it can be directly used in the controller as follows:
class MechanicController extends Controller { public function getIndex() { \AjaxResponse::success(); }}
Its function is to standardize the returned format
{ code: "0" result: { }}
Create a Service class
Create a class in the app/Services folder
$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); }}
This AjaxResponse is a specific implementation class. below we will make a provider for this class
Create provider
Create a class in the app/Providers folder
app->singleton('AjaxResponseService', function () { return new \App\Services\AjaxResponse(); }); }}
In register, we define this Service name as AjaxResponseService.
Next, we will define a facade.
Create a facade
Create a class in the app/Facades folder
Modify configuration fileNow, we only need to mount these two things to app. php.
[ ... 'App\Providers\RouteServiceProvider', 'App\Providers\AjaxResponseServiceProvider', ], 'aliases' => [ ... 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', 'AjaxResponse' => 'App\Facades\AjaxResponseFacade', ],];
SummaryIn laravel5, it is easier to use facade, which is basically the same as 4.