laravel5创建service provider和facade的方法详解
本文实例讲述了laravel5创建serviceprovider和facade的方法。分享给大家供大家参考,具体如下:
laravel5创建一个facade,可以将某个service注册个门面,这样,使用的时候就不需要麻烦地use了。文章用一个例子说明怎么创建serviceprovider和facade。
目标
我希望我创建一个AjaxResponse的facade,这样能直接在controller中这样使用:
classMechanicControllerextendsController{ publicfunctiongetIndex() { \AjaxResponse::success(); } }
它的作用就是规范返回的格式为
{ code:"0" result:{ } }
步骤
创建Service类
在app/Services文件夹中创建类
<?phpnamespaceApp\Services; classAjaxResponse{ protectedfunctionajaxResponse($code,$message,$data=null) { $out=[ 'code'=>$code, 'message'=>$message, ]; if($data!==null){ $out['result']=$data; } returnresponse()->json($out); } publicfunctionsuccess($data=null) { $code=ResultCode::Success; return$this->ajaxResponse(0,'',$data); } publicfunctionfail($message,$extra=[]) { return$this->ajaxResponse(1,$message,$extra); } }
这个AjaxResponse是具体的实现类,下面我们要为这个类做一个provider
创建provider
在app/Providers文件夹中创建类
<?phpnamespaceApp\Providers; useIlluminate\Support\ServiceProvider; classAjaxResponseServiceProviderextendsServiceProvider{ publicfunctionregister() { $this->app->singleton('AjaxResponseService',function(){ returnnew\App\Services\AjaxResponse(); }); } }
这里我们在register的时候定义了这个Service名字为AjaxResponseService
下面我们再定义一个门脸facade
创建facade
在app/Facades文件夹中创建类
<?phpnamespaceApp\Facades; useIlluminate\Support\Facades\Facade; classAjaxResponseFacadeextendsFacade{ protectedstaticfunctiongetFacadeAccessor(){return'AjaxResponseService';} }
修改配置文件
好了,下面我们只需要到app.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', ], ];
总结
laravel5中使用facade还是较为容易的,基本和4没啥区别。
更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。