laravel Service Provider

来源:互联网 发布:表格分析数据怎么取消 编辑:程序博客网 时间:2024/06/01 09:49

转载请注明: 转载自Yuansir-web菜鸟 | LAMP学习笔记

Service Provider可以把相关的 IoC 注册放到到同一个地方,大部份的 Laravel 核心组件都有Service Provider,所有被注册的服务提供者都列在 app/config/app.php 配置文件的 providers 数组里。如何写一个Service Provider手册里面写的也比较简洁,实际项目中如何运用还是有点模糊,这里来简单写一个实例,便于理解和实际项目中扩展使用,也许对IOC和依赖注入都有个更深刻的了解。

和《Laravel 创建 Facades 实例》类似,先在app目录下新建目录app/libs/App/Service,所有的Service都放在这个Service下面,然后在composer.json中添加:

1"autoload": {
2    ......
3        "psr-0":{
4            "App":"app/libs"
5        }
6},

App的命名空间随意定,执行下composer dump

建立一个TestService,新建目录app/libs/App/Service/Test, 简单写一个ServiceInterface并实现。

app/libs/App/Service/Test/TestServiceInterface.php代码很简单:

1<?php namespace App\Service\Test;
2 
3interface TestServiceInterface {}

app/libs/App/Service/Test/TestService.php代码很简单:

1<?php namespace App\Service\Test;
2 
3class TestServiceimplements TestServiceInterface {
4    publicfunction callMe()
5    {
6        dd('this is the test service');
7    }
8}

接下来就是定义一个Service Providor,新建app/libs/App/Service/ServiceServiceProvidor.php, 代码如下:

01<?php namespace App\Service;
02 
03use Illuminate\Support\ServiceProvider;
04 
05class ServiceServiceProviderextends ServiceProvider {
06 
07    /**
08     * IoC binding of the service.
09     *
10     * @return void
11     */
12    publicfunction register()
13    {
14 
15        $namespace= 'App\Service\\';
16 
17        $services= [
18            $namespace. 'Test\TestServiceInterface'=> $namespace . 'Test\TestService',
19        ];
20 
21        foreach($services as $interface => $instance) {
22            $this->app->bind($interface,$instance);
23        }
24 
25    }
26 
27}

register 通过 $this->app->bind 使用IoC 容器。

把’App\Service\ServiceServiceProvider‘加到配置文件app/config/app.php的 providers 数组。
OK了,在HomeController中来测试一下:

01<?php
02use App\Service\Test\TestServiceInterface;
03 
04class HomeControllerextends BaseController {
05 
06    /*
07    |--------------------------------------------------------------------------
08    | Default Home Controller
09    |--------------------------------------------------------------------------
10    |
11    | You may wish to use controllers instead of, or in addition to, Closure
12    | based routes. That's great! Here is an example controller method to
13    | get you started. To route to this controller, just add the route:
14    |
15    |   Route::get('/', 'HomeController@showWelcome');
16    |
17    */
18 
19    publicfunction __construct(TestServiceInterface$test)
20    {
21        $this->test =$test;
22    }
23 
24    publicfunction showWelcome()
25    {
26        $this->test->callMe();
27        returnView::make('hello');
28    }
29 
30}

输出 this is the test service

0 0
原创粉丝点击