【问题标题】:Dependency injection in Laravel service layer classLaravel 服务层类中的依赖注入
【发布时间】:2020-05-01 15:50:10
【问题描述】:

在我的 Laravel 6.9.0 应用程序中,我有一些代码需要在很多地方运行,因此我正在努力将其创建为服务层。

我已创建文件 /app/Actions/Music/GetRecentArtists.php 并将其添加到我的作曲家自动加载配置中:

<?php

namespace App\Actions\Music;

use \Barryvanveen\Lastfm\Lastfm;

class GetRecentArtists {

    public function get(Lastfm $lastfm)
    {
        return true;
    }

}

但是当我在 Tinker 中使用:

(new App\Actions\Music\GetRecentArtists())->get()

我收到以下错误:

TypeError: Too few arguments to function App/Actions/Music/GetRecentArtists::get(), 0 passed in Psy Shell code on line 1 and exactly 1 expected

我认为依赖注入会注入Lastfm 实例。当我删除函数参数时,它运行良好。

【问题讨论】:

  • 与依赖注入无关,但使用scope 可能会更好。
  • Barryvanveen\Lastfm\Lastfm 类在哪里?在作曲家文件中加载并运行 dumpautoload 命令的最佳方法
  • Laravel 依赖注入只有在你从服务容器中拉取 GetRecentArtists 时才有效。如果你自己创建它是行不通的。

标签: php laravel dependency-injection service-layer


【解决方案1】:

如果你使用resolve 方法,Laravel 服务容器应该为你注入依赖:

resolve('App\Actions\Music\GetRecentArtists')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 2014-02-25
    • 2020-01-17
    • 1970-01-01
    • 2016-01-26
    • 2014-02-02
    • 1970-01-01
    • 2020-09-09
    相关资源
    最近更新 更多