【问题标题】:Is it possible to inject a repository as a dependency in a laravel service file?是否可以将存储库作为依赖项注入到 laravel 服务文件中?
【发布时间】:2016-12-22 11:26:57
【问题描述】:

我正在尝试做的 - 1)控制器将依赖于逻辑和东西的服务。 2) 依赖于存储库进行数据库访问的服务。 3)控制器将作为依赖项获得服务。 4) 服务将获得一个存储库作为依赖项。

我的服务等级是 -

class AnimeService implements IAnimeService{

    protected $animeRepository;

    public function _construct(IAnimeRepository $_animeRepository) {       
        $this->animeRepository = $_animeRepository;
    }

    public function add(Anime $anime) {      
        return $this->animeRepository->add($anime);
    }
}

问题是——

Call to a member function add() on null

这是预期的 - 因为 _construct 永远不会被调用。

顺便说一句;来自我的 AppServiceProvider

public function register()
    {
        $this->app->bind('\App\Services\Interfaces\IAnimeService', '\App\Services\Implementations\AnimeService');
        $this->app->bind('\App\Repositories\Interfaces\IAnimeRepository', '\App\Repositories\Implementations\AnimeRepository');
    }

我的问题是—— 1) 在这种情况下,我该怎么做才能使我的服务正常工作?

2) 最佳做法是什么?

3) 还有哪些其他方法可以实现我想要做的事情?

谢谢。

【问题讨论】:

    标签: php laravel service laravel-5 repository


    【解决方案1】:

    构造函数应该命名为__construct而不是_construct,并带有两个下划线:) 请参阅 php 文档:http://php.net/manual/en/language.oop5.decon.php

    如果你在控制器构造函数中注入AnimeService,Laravel 应该会自动解析依赖关系,所以它应该可以通过修复构造函数方法的名称来处理你在这里的内容:)

    【讨论】:

    • 是的,每个人都会出现拼写错误;)而且我敢肯定,当每个人发现这是错误时都会很生气 xD
    猜你喜欢
    • 2019-09-04
    • 2023-03-23
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多