简体   繁体   English

Laravel和依赖注入方案

[英]Laravel and dependency Injection Scenario

I have the following code 我有以下代码

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
    }

}

How can i inject the HomeController, PageController as a delegate in FooBar class ? 我如何在FooBar类中将HomeController,PageController注入为委托?

with the above code i get the a missing argument error 与上面的代码,我得到一个缺少参数错误

Dependency Injection in Laravel is as simple as that: 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 will be instantiated and injected as $delegate. Home Controller将被实例化并作为$ delegate注入。

EDIT: 编辑:

But if you need to instantiate FooBar passing the instantiator (your controller) to it, you have to do it this way: 但是,如果您需要实例化将实例化器(您的控制器)传递给它的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));
    }

}

Try This. 尝试这个。 ( http://laravel.com/docs/ioc#automatic-resolution ) 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