如何在Laravel 4中处理具有控制器继承的存储库/接口?

时间:2013-08-01 11:42:45

标签: php oop interface laravel laravel-4

我在控制器中使用存储库/接口时遇到问题。我的应用正在使用Laravel 4。

我当前的控制器继承树是:

 +- BaseController
     +- FrontendController
         +- ProductController

FrontendController中我正在设置/设置一些在我的控制器中使用的东西,所以我在构造函数中设置了接口,如下所示:

class FrontendController extends BaseController
{
    /**
     * Constructor
     */
    public function __construct(SystemRepositoryInterface $system,
                                BrandRepositoryInterface $brands,
                                CategoryRepositoryInterface $categories)

然而,现在这意味着我必须通过接口(再次)发送所有子控制器,如下所示:

class ProductController extends FrontendController
{
    /**
     * Constructor
     */
    public function __construct(SystemRepositoryInterface $system,
                                BrandRepositoryInterface $brands,
                                CategoryRepositoryInterface $categories,
                                ProductRepositoryInterface $products)
    {
        parent::__construct($system, $brands, $categories);

我是PHP的这个级别/领域的新手,但感觉不对,我错过了一些明显的东西吗?

1 个答案:

答案 0 :(得分:1)

不,你没错。 PHP不像其他语言那样支持方法重载。所以你必须每次都重写FrontendController的构造函数(Bro tip:一个好的IDE应该在这里帮助你很多;>)。 Laravel通过其IoC-Container解析所有控制器构造函数依赖项。只需添加

App::bind('SystemRepositoryInterface', function() {
    return new EloquentSystemRepository();
});

用于应用程序的某个引导程序文件中的每个存储库。框架将为您进行注射。