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