0

我有以下代码

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
    }

}

如何在 FooBar 类中注入 HomeController、PageController 作为委托?

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

4

2 回答 2

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

}
于 2013-11-13T00:37:40.200 回答
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;
});
于 2013-11-13T00:39:10.240 回答