laravel:服务容器(10.27.0)
一,相关文档:
https://learnku.com/docs/laravel/10.x/container/14842
二,php代码:
假设我们有两种商品:虚拟商品如账号,实体商品如手办需要销售
1,App\extend\mall\GoodsInterface.php
|
1
2
3
4
5
6
7
|
<?phpnamespace App\extend\mall;//接口interface GoodsInterface{ public function sale();} |
2,App\extend\mall\RealGoods.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?phpnamespace App\extend\mall;//实体商品class RealGoods implements GoodsInterface{ private $name = ''; public function __construct($name) { $this->name = $name; } public function sale() { echo '实体商品:'.$this->name. '下订单,减库存,通知发货<br/>'; }} |
3,App\extend\mall\VirtualGoods.php
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?phpnamespace App\extend\mall;//虚拟商品class VirtualGoods implements GoodsInterface{ private $name = ''; public function __construct($name) { $this->name = $name; } public function sale() { echo '虚拟商品:'.$this->name. '下订单,无需减库存,生成虚拟商品并通知用户<br/>'; }} |
4,App\extend\mall\GoodsSale.php
|
1
2
3
4
5
6
7
8
9
|
<?phpnamespace App\extend\mall;//销售功能class GoodsSale{ public function saleOne(GoodsInterface $goods) { $goods->sale(); }} |
5,routes/web.php中添加:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
Route::get('container/test', function(){ app()->bind('RealGoods', function(){ return new \App\extend\mall\RealGoods('手办'); }); app()->instance('VirtualGoods', new \App\extend\mall\VirtualGoods('账号')); app()->singleton('GoodsSale', function(){ return new \App\extend\mall\GoodsSale(); }); $goodsSale = app()->make('GoodsSale'); $rgoods = app()->make('RealGoods'); $goodsSale->saleOne($rgoods); $vgoods = app()->make('VirtualGoods'); $goodsSale->saleOne($vgoods);}); |
6,相关说明:
上面的代码:通过saleOne方法的参数把对象注入进来,
app():用来生成容器。
bind(): 直接绑定一个容器对象。
instance():绑定一个实例化对象。
singleton(): 绑定一个单例对象。
绑定完成之后,make() 方法来获得容器中的对象实例
三,查看效果:

四,查看laravel框架的版本:
liuhongdi@lhdpc:/data/laravel/dignews$ php artisan --version
Laravel Framework 10.27.0

浙公网安备 33010602011771号