繁体   English   中英

Laravel和依赖注入方案

[英]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
    }

}

我如何在FooBar类中将HomeController,PageController注入为委托?

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

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

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM