laravel容器
原创
©著作权归作者所有:来自51CTO博客作者廖圣平_的原创作品,请联系作者获取转载授权,否则将追究法律责任
本文为demo,更详情请查看这里
电脑有键盘,比方:雷蛇,双飞燕。
有时候使用双飞燕,有时候雷蛇
这两个统称为键盘,所以写一个接口类
interface Board
{
public function attr();//键盘的属性
}
创建两个类:
LeiShe.php
<?php
namespace App\Services\Test\board;
use App\Services\Test\Board;
class LeiShe implements Board
{
public $attr='雷蛇键盘';
public function attr()
{
return $this->attr;
}
}
ShuangFeiYan.php
<?php
namespace App\Services\Test\board;
use App\Services\Test\Board;
class ShuangFeiYan implements Board
{
public $attr='双飞燕键盘';
public function attr()
{
return $this->attr;
}
}
创建 Provider
php artisan make:provider TestService
在 app/Providers
生成:TestServiceProvider.php
<?php
namespace App\Providers;
use App\Services\Test\Computer;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->singleton('LeiShe','App\Services\Test\board\LeiShe');//雷蛇
$this->app->bind('ShuangFeiYan','App\Services\Test\board\ShuangFeiYan');//双飞燕
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
现在你可以在程序中使用
echo app('LeiShe')->attr();
singleton实现的是单例模式;
bind: new 对象
其他扩展:
Computer.phlp
<?php
namespace App\Services\Test;
class Computer
{
/**
* @var
*/
public $board;
function __construct(Board $board)
{
$this->board = $board;
}
public function attr(){
return $this->board->attr();
}
}
提供者:
class TestServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->singleton('LeiShe','App\Services\Test\board\LeiShe');//雷蛇
$this->app->singleton('ShuangFeiYan','App\Services\Test\board\ShuangFeiYan');//双飞燕
//触发事件
$this->app->resolving('ShuangFeiYan',function ($object, $container){
$object->memo = '初始化的值';
$leishe = $container->make('LeiShe');
$leishe->memo = '初始化雷蛇的默认值';
});
$this->app->bind('Computer',function ($container){
return new Computer($container->make('ShuangFeiYan'));//使用双飞燕键盘
});
}
和我做朋友?