本文實例講述了laravel5創建service provider和facade的方法。分享給大家供大家參考,具體如下:
laravel5建立一個facade,可以將某個service註冊個門面,這樣,使用的時候就不需要麻煩地use 了。文章用一個範例說明怎麼建立service provider和 facade。
目標
我希望我創建一個AjaxResponse的facade,這樣能直接在controller中這樣使用:
class MechanicController extends Controller { public function getIndex() { \AjaxResponse::success(); } }
它的作用是規範返回的格式為規範返回的格式。
創建Service類別在app/Services資料夾中建立類別{ code: "0" result: { } }
<?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); } }
修改設定檔好了,下面我們只需要到app.php中掛載上這兩個東東就可以了
<?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(); }); } }