laravel5创建service provider和facade的方法详解

2025-05-29 0 79

本文实例讲述了laravel5创建service providerfacade的方法。分享给大家供大家参考,具体如下:

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

目标

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

?

1

2

3

4

5

6
class MechanicController extends Controller {

public function getIndex()

{

\\AjaxResponse::success();

}

}

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

?

1

2

3

4

5
{

code: "0"

result: {

}

}

步骤

创建Service

在app/Services文件夹中创建类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23
<?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文件夹中创建类

?

1

2

3

4

5

6

7

8

9

10
<?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文件夹中创建类

?

1

2

3

4

5
<?php namespace App\\Facades;

use Illuminate\\Support\\Facades\\Facade;

class AjaxResponseFacade extends Facade {

protected static function getFacadeAccessor() { return 'AjaxResponseService'; }

}

修改配置文件

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15
<?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框架的PHP程序设计有所帮助。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 laravel5创建service provider和facade的方法详解 https://www.kuaiidc.com/96709.html

相关文章

发表评论
暂无评论