简体   繁体   English

Laravel 服务层类中的依赖注入

[英]Dependency injection in Laravel service layer class

In my Laravel 6.9.0 app, I have some code which I need to run from many places, so I'm working on creating this as a service layer.在我的 Laravel 6.9.0 应用程序中,我有一些代码需要从很多地方运行,所以我正在努力将其创建为服务层。

I've created the file /app/Actions/Music/GetRecentArtists.php and added it to my composer autoload config:我已经创建了文件/app/Actions/Music/GetRecentArtists.php并将其添加到我的作曲家自动加载配置中:

<?php

namespace App\Actions\Music;

use \Barryvanveen\Lastfm\Lastfm;

class GetRecentArtists {

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

}

But when I run it in Tinker using:但是当我在 Tinker 中使用以下命令运行它时:

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

I get the following error:我收到以下错误:

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

I'd thought that dependency injection would inject the Lastfm instance.我原以为依赖注入会注入Lastfm实例。 When I remove the function argument, it runs fine.当我删除函数参数时,它运行良好。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM