【问题标题】:Laravel 4: how to inject another class in a eloquent modelLaravel 4:如何在 eloquent 模型中注入另一个类
【发布时间】:2013-07-20 23:28:25
【问题描述】:

我正在尝试使用内置的 laravel 的 Ioc 容器在 Page 模型中注入一个 PageManager 类,我有点迷路了。

我想要达到的目标是这样的:

class Pages extends Eloquent {

    public function __construct(PagesManagerInterface $manager, array $attributes = array()) 
    {
        parent::__construct($attributes);
        $this->manager = new $manager;
    }

    public function saveToDisk()
    {
         $this->manager->writeToFile();
    }

但我收到此错误:

ErrorException:传递给 Pages::__construct() 的参数 1 必须是 PagesManagerInterface 的实例,没有给出。

我尝试在 app/start/global.php 中添加这个:

App::bind('Pages',function(){

    return new Pages(new PagesManager);
});

但似乎被框架忽略了,我也不知道如何将 $attribute 数组插入到这个声明中。

我有点迷茫,所以感谢任何帮助!

【问题讨论】:

  • 尝试使用Facade::swap()方法。
  • 您能详细说明一下吗?谢谢。

标签: dependency-injection laravel inversion-of-control ioc-container


【解决方案1】:

在 Laravel 中,您可以使用 IoC 容器

public function saveToDisk(){
    $managerObject = app()->make('path\to\class\PagesManagerInterface');
    $managerObject->writeToFile();
}

【讨论】:

    【解决方案2】:

    我认为你需要的是:

    App::bind('PagesManagerInterface',function(){
    
        return new Pages(new PagesManager);
    
    });
    

    这告诉 Laravel 每次需要一个 PagesManagerInterface 实例时注入一个新的 Page 对象,而创建模型时没有传递该实例。

    【讨论】:

    • 感谢您的建议,无论如何,我最终只在需要页面作为参考时才实例化管理器。
    【解决方案3】:

    重载模型的构造函数不是一个好主意,因为可以通过各种方法在后台生成新实例,例如 Model::find()。

    发生这种情况时,您在自定义构造函数中请求的依赖项不会被传入,因为 Model 类不知道它们。因此,您会收到该错误消息。

    在此处查看 find() 方法:http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#380-397

    查看 Jason Lewis 的这篇帖子:http://forums.laravel.io/viewtopic.php?pid=47124#p47124

    【讨论】:

    • 这很好,我实际上只在需要时才实例化管理器并将页面作为参考传递。
    猜你喜欢
    • 2012-11-28
    • 2013-01-30
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 2021-09-07
    • 2018-11-26
    相关资源
    最近更新 更多