简体   繁体   English

从Artisan Command中的Controller运行方法?

[英]Running method from Controller in Artisan Command?

In my custom Artisan command I fetch a list of items from my DB, I would like to iterate through them and run them through a method from my DownloaderController. 在我的自定义Artisan命令中,我从数据库中获取了一个项目列表,我想遍历它们并通过DownloaderController中的方法运行它们。 How can I do this? 我怎样才能做到这一点? and what is the best practise? 最佳实践是什么?

DownloadCommand.php DownloadCommand.php

public function handle()
    {
        $files = File::all();

        foreach($files as $file)
        {
            // downloadFile method belongs to DownloadController
            downloadFile($file);
        }
    }

DownloadController.php DownloadController.php

public function downloadFile($file)
{
    // some example logic to download file
    if(wget($file))
    {
        $file->status = 'Downloaded';
    }
    else
    {
        $file->status = 'Failed';
    }

    $file->save();
}

Logic responsible for fetching data shouldn't be included in your controller. 负责获取数据的逻辑不应包含在控制器中。 Create a repository (or a specialized service) for that, and inject it to your command. 为此创建一个存储库(或专用服务),并将其注入到您的命令中。

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

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