拉拉维尔和依赖注入方案


Laravel and dependency Injection Scenario

>我有以下代码

class FooBar
{
    protected $delegate;
    public function __construct( $delegate )
    {
        $this->delegate = $delegate;
    }
}
App::bind('FooBar', function()
{
    return new FooBar();
});
class HomeController extends BaseController 
{
    protected $fooBar;
    public function __construct()
    {
        $this->fooBar = App::make('FooBar');
        //HomeController needs to be injected in FooBar class
    }
}
class PageController extends BaseController 
{
    protected $fooBar;
    public function __construct()
    {
        $this->fooBar = App::make('FooBar');
        // PageController needs to be injected in FooBar class
    }
}

如何将 HomeController, PageController 作为 FooBar 类中的委托注入?

使用上面的代码,我得到缺少参数错误

Laravel中的依赖注入就是这么简单:

class FooBar
{
    protected $delegate;
    public function __construct( HomeController $delegate )
    {
        $this->delegate = $delegate;
    }
}
App::bind('FooBar', function()
{
    return new FooBar();
});
class HomeController extends BaseController 
{
    protected $fooBar;
    public function __construct()
    {
        $this->fooBar = App::make('FooBar');
    }
}

主控制器将作为$delegate进行实例化和注入。

编辑:

但是如果你需要实例化FooBar,将实例化器(你的控制器)传递给它,你必须这样做:

<?php
class FooBar
{
    protected $delegate;
    public function __construct( $delegate )
    {
        $this->delegate = $delegate;
        /// $delegate here is HomeController, RegisterController, FooController...
    }
}
App::bind('FooBar', function($app, $param) 
{
    return new FooBar($param);
});
class HomeController extends Controller {
    protected $fooBar;
    public function delegate()
    {
        $this->fooBar = App::make('FooBar', array('delegate' => $this));
    }
}

试试这个。(http://laravel.com/docs/ioc#automatic-resolution)

class FooBar
{
    protected $delegate;
    public function __construct( HomeController $delegate )
    {
        $this->delegate = $delegate;
    }
}
App::bind('FooBar', function($delegate)
{
    return new FooBar;
});