laravel-4将需要配置的对象注入控制器的方法 [英] laravel-4 way to inject an object that requires configuration into a controller

查看:118
本文介绍了laravel-4将需要配置的对象注入控制器的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一种将预配置对象传递给控制器​​的好方法.我知道我可以像下面那样使用IoC:

I would like to find a good way to pass a pre-configured object to a controller. I know that I can use the IoC like below:

Mycontroller extends extends \Illuminate\Routing\Controllers\Controller {

    //i can only use one config uless i pass Request data
    $this->config = App::make('MyconfigObject');

}

但是这似乎有只能使用一个配置的局限性.我宁愿做如下事情:

but this seems to have the limitation of only being able to use one config. I would rather do something like the following:

Route::get('some-route', function()
{
    $config = Config::get('some.config');
    $object = new MyConfigObject($config);
    Route::dispatch(MyController($object));
});

之所以要这样做,是因为我想分派相同的控制器,但对多个路由使用不同的配置.

The reason I would like to do this is that I would like to dispatch the same controller, but with different configuration for several routes.

推荐答案

我对这种方法并不完全满意,但是到目前为止,我已经使用IoC的自动分辨率提出了最好的方法.

I'm not totally satisfied with this method but its the best I've come up with so far, using the IoC's automatic resolution.

bootstrap/stat.php

bootstrap/stat.php

/*
* bindings to the IoC container
*/
$app->singleton('MyNamespace\Transfer\TransferStategyInterface', function() {
    $config = Config::get('transfer-strategy');
    return new LocalTransferStrategy($config);
});


use MyNamespace\Transfer\TransferStategyInterface;

TransferController.php

TransferController.php

use MyNamespace\Transfer\TransferStategyInterface;


class TransferController extends BaseController {

    protected $transferStrategy;

    public function __construct(TransferStategyInterface $transferStrategy = null)
    {
        $this->transferStrategy = $transferStrategy;
    }
}

这篇关于laravel-4将需要配置的对象注入控制器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆