Laravel和依赖注入场景

时间:2013-11-12 23:47:10

标签: php dependency-injection laravel laravel-4

我有以下代码

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类中的委托注入?

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

2 个答案:

答案 0 :(得分:0)

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

}

Home Controller将被实例化并注入$ 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));
    }

}

答案 1 :(得分:0)

试试这个。 (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;
});