您的位置:首页 > 编程语言 > PHP开发

laravel Service Provider

2015-06-17 09:55 585 查看
转载请注明: 转载自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
 
3
interface
TestServiceInterface {}
app/libs/App/Service/Test/TestService.php代码很简单:

1
<?php namespace App\Service\Test;
2
 
3
class
TestService
implements
TestServiceInterface {
4
    
public

function
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
 
03
use
Illuminate\Support\ServiceProvider;
04
 
05
class
ServiceServiceProvider
extends
ServiceProvider {
06
 
07
    
/**
08
     
* IoC binding of the service.
09
     
*
10
     
* @return void
11
     
*/
<
ca79
/tbody>
12
    
public

function
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
02
use
App\Service\Test\TestServiceInterface;
03
 
04
class
HomeController
extends
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
    
public

function
__construct(TestServiceInterface
$test
)
20
    
{
21
        
$this
->test =
$test
;
22
    
}
23
 
24
    
public

function
showWelcome()
25
    
{
26
        
$this
->test->callMe();
27
        
return

View::make(
'hello'
);
28
    
}
29
 
30
}
输出 this is the test service
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息