神秘面纱,有时候不去阅读它,会觉得它好牛,好牛逼!
版本说明
laravel5.2,其他版本查看对应手册,后续会出5.3,5.4,5.5,5.6不断补充。
官方简介
所有Laravel应用启动的中心,所有Laravel的核心服务都是通过服务提供者启动,服务提供者是应用配置的中心.
这里需要了解下IOC(控制反转)也叫依赖注入。这个IOC打算另外一篇文章将,到时候再贴链接
使用原则
如果一个类没有基于任何接口那么就没有必要将其绑定到容器,如果一个简单的类,就不需要这么做,因为这样做多余。
创建一个服务提供者
创建之后文件所在地:app/Providers/下
php artisan make:provider TestServiceProvider
加入组织,不然会找不到,config/app.php
'providers' => [
...
App\Providers\TestServiceProvider::class,
]
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class TestController extends Controller
{
//
}
1.boot函数
这个一般都是写逻辑的引导,可以参考自定义Blade指令那篇文章了解
#EXP
public function boot()
{
view()->composer('view', function () {
//
});
}
2.regist函数
注册或绑定的意思,注册就是告诉我们应用,我这个函数已经注册了,你可以通过它实现依赖,否则会说不能注入依赖
2.1 注册方法
使用singleton绑定单例,这种方式,无需写引入命名空间,直接调用别名即可
$this->app->singleton('test',function(){
return new TestService();
});
//或
//$this->app->singleton('test','App\Services\TestService');
这里的"test"表示绑定实例的别名,后面对应一个匿名函数,表示实现的方法,当然也可以直接写类
这个如何调用呢,通过App::make去调用或者app()函数注册
$test = App::make('test');//或 $this->app->make('test');或app('test')
$test->callMe('TestController');
使用bind绑定实例到接口以便依赖注入
$this->app->bind('App\Contracts\TestContract',function(){
return new TestService();
});
//或
//$this->app->bind('App\Contracts\EventPusher', 'App\Services\TestService');
这里的'App\Contracts\TestContract',可以认为,当你需要用这个依赖注入的时候,去执行后面的匿名函数,这里同样都可以直接写类
第一个参数可以认为是名字,第二个是实现方式。
调用形式
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App;
use App\Http\Requests;
use App\Contracts\TestContract;
//use App\Services\TestService as Test;
class TestController extends Controller
{
//TestContract $test
//依赖注入
public function __construct( TestContract $test){
$this->test = $test;
}
public function index()
{
$this->test->callMe(222);;
return view('index');
}
}
instance注册实例
$test_Service= new TestService();
$this->app->instance('TestService', $test_Service);//第一个参数是名字,
调用
$this->app->make('TestService');或$this->app['TestService'];
tag标签使用
$this->app->bind('SpeedReport', function () {
//
});
$this->app->bind('MemoryReport', function () {
//
});
$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');
//调用
$test = App::make('reports');//或$test = $this->app->make('reports');或app('reports')
$test->callMe('TestController');
事件
有点类似说,JS的监听事件,比如你点击的监听时间。
$this->app->resolving(function ($object, $app) {
// 容器解析所有类型对象时调用
});
$this->app->resolving(function (FooBar $fooBar, $app) {
// 容器解析“FooBar”对象时调用
});
其他方法,看手册吧,都是比较简单
实现例子参考这个文档,这里不再啰嗦
http://laravelacademy.org/post/796.html
网友评论