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

760 查看

<?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'));
});