php - Laravel 无法通过 __construct 实例化接口(interface)(使用 App::bind)

标签 php laravel laravel-4

我正在尝试使用 Laravel 的 bind() 方法通过 __construct 解析类。

这是我所做的:

routes.php(当然我会把它从这里移走)

// Bindings
App::bind(
    'License\Services\ModuleSelector\SelectorInterface',
    'License\Services\ModuleSelector\ModuleSelector'
);

SelectorInterface.php - 我期望在 __construct 方法中使用的接口(interface)。

<?php namespace License\Services\ModuleSelector;


interface SelectorInterface {

    /**
     * Simply return query that will select needle module fields
     *
     * @return mixed
     */
    public function make();

}

ModuleSelector.php - 这是我想通过 Laravel 的 DI 解析的类(请参见下面的示例)。

<?php namespace License\Services\ModuleSelector;    

use License\Services\ModuleSelector\Selector;   

class ModuleSelector extends Selector
{       
    /**
     * Get module by it's code
     *
     * @return mixed
     */
    public function find()
    {
        return $this->make()
            ->where('code', $module_code)
            ->first();
    }    
}

Module.php

<?php namespace License\Services\ModuleType;    

use License\Services\ModuleType\TypeInterface;
use License\Services\ModuleSelector\SelectorInterface;    

class Module 
{    
    ...    

    function __construct(SelectorInterface $selector)
    {
        $this->selector = $selector;
    }
    ...
}

以及发生错误的地方:

在我的存储库中,我使用 License\Services\ModuleType\Module 作为 ModuleService;

有一个名为 find() 的方法:

/**
 * Find module by its code with all data (types, selected type)
 * @return mixed
 */
public function find($module_code)
{
    $module = new ModuleService;

    // Get module id in order to use build in relations in framework
    $module = $this->module->find($module_code);

    ...
}

所以,换句话说,我有 2 个类和 1 个接口(interface)。我想做的是:

1) 创建Class1.php/Class2.php/Class2Interface.php

2) 在 Class1.php__construct 中,我指定 __construct(Class2Interface $class2)

3) 实例化Class2

我做错了什么?找到的示例 here .

最佳答案

在这一行中:

$module = new ModuleService;

您直接调用 Module 类,而不传入 SelectorInterface 的实例。

为了使 IoC 工作,您需要绑定(bind)使用它创建类。再次尝试该行:

$module = App::make('License\Services\ModuleSelector\SelectorInterface');

另一种选择是将其直接注入(inject)到您的存储库构造函数中,只要存储库是由 IoC 容器创建的,您的具体内容就会自动注入(inject)。

关于php - Laravel 无法通过 __construct 实例化接口(interface)(使用 App::bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24861279/

相关文章:

javascript - 使用 AJAX 的 Laravel 5 jQuery

routes - 命名路由和静态 Controller 问题

laravel-4 - Laravel Eloquent hasManyThrough 关系,SELECT 没有

javascript - 我想使用 Javascript 来放置 Php 函数

php - dompdf 不显示由 PHP 文件生成的图像

php - Laravel foreach 每个项目递增 3

php - 如何在html表格中打印多行查询结果?

php - 如何在 Laravel 的 Controller 中捕获异常?

php - 如何查找 Magento 布局文件的来源

php - MySQL/PHP 计数