首页 技术 正文
技术 2022年11月13日
0 收藏 889 点赞 2,458 浏览 1669 个字

laravel5如何创建service provider和facade

laravel5创建一个facade,可以将某个service注册个门面,这样,使用的时候就不需要麻烦地use 了。文章用一个例子说明怎么创建service provider和 facade。

目标

我希望我创建一个AjaxResponse的facade,这样能直接在controller中这样使用:

class MechanicController extends Controller {    public function getIndex()
{
\AjaxResponse::success();
}
}

它的作用就是规范返回的格式为

{
code: "0"
result: { }
}

步骤

创建Service类

在app/Services文件夹中创建类

<?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是具体的实现类,下面我们要为这个类做一个provider

创建provider

在app/Providers文件夹中创建类

<?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名字为AjaxResponseService

下面我们再定义一个门脸facade

创建facade

在app/Facades文件夹中创建类

<?php namespace App\Facades;use Illuminate\Support\Facades\Facade;class AjaxResponseFacade extends Facade {    protected static function getFacadeAccessor() { return 'AjaxResponseService'; }}

修改配置文件

好了,下面我们只需要到app.php中挂载上这两个东东就可以了

<?phpreturn [    ...    '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没啥区别。

下一篇: css特效
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,906
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,739
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,131
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293