《PHP實例:laravel5創(chuàng)建service provider和facade的方法詳解》要點:
本文介紹了PHP實例:laravel5創(chuàng)建service provider和facade的方法詳解,希望對您有用。如果有疑問,可以聯(lián)系我們。
本文實例講述了laravel5創(chuàng)建service provider和facade的方法.分享給大家供大家參考,具體如下:PHP實例
laravel5創(chuàng)建一個facade,可以將某個service注冊個門面,這樣,使用的時候就不需要麻煩地use 了.文章用一個例子說明怎么創(chuàng)建service provider和 facade.PHP實例
目標(biāo)PHP實例
我希望我創(chuàng)建一個AjaxResponse的facade,這樣能直接在controller中這樣使用:PHP實例
class MechanicController extends Controller { public function getIndex() { \AjaxResponse::success(); } }
它的作用就是規(guī)范返回的格式為PHP實例
{ code: "0" result: { } }
步驟PHP實例
創(chuàng)建Service類PHP實例
在app/Services文件夾中創(chuàng)建類PHP實例
<?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); } }
這個AjaxResponse是具體的實現(xiàn)類,下面我們要為這個類做一個providerPHP實例
創(chuàng)建providerPHP實例
在app/Providers文件夾中創(chuàng)建類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(); }); } }
這里我們在register的時候定義了這個Service名字為AjaxResponseServicePHP實例
下面我們再定義一個門臉facadePHP實例
創(chuàng)建facadePHP實例
在app/Facades文件夾中創(chuàng)建類PHP實例
<?php namespace App\Facades; use Illuminate\Support\Facades\Facade; class AjaxResponseFacade extends Facade { protected static function getFacadeAccessor() { return 'AjaxResponseService'; } }
修改配置文件PHP實例
好了,下面我們只需要到app.php中掛載上這兩個東東就可以了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', ], ];
總結(jié)PHP實例
laravel5中使用facade還是較為容易的,基本和4沒啥區(qū)別.PHP實例
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php日期與時間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》PHP實例
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助.PHP實例
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/5068.html