laravel的ioc容器——单例绑定方法

<?php
class Base{

}
class Bar{
    private $base;
    // type in
    public function __construct(Base $base)
    {
        $this->base = $base;
    }
}
class Foo
{
    private $bar;
    // type in
    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
}

// 如果使用bind方法绑定了,那么laravel将会使用bind方法绑定的方式,不再使用type in 的方式
App::bind('Foo', function(){
    return new Foo(new Bar(new Base));
});

// laravel的参数,加入类型type in,laravel将会自动实现new class()的操作,避免耦合的情况出现
Route::get('/', function () {
    // 读取single单例绑定的对象
    // 1.make方式,
    // dd( app()->make('files')->get(__DIR__.'/Kernel.php') );
    // 2.数组方式
    // dd( app()['files']->get(__DIR__.'/Kernel.php') );
    // 3.参数方式
    // dd( app('files')->get(__DIR__.'/Kernel.php') );

    // 调用bind方法调用绑定的对象
    dd(app('Foo'));
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值