Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Artisan命令中从控制器运行方法?_Php_Laravel_Laravel Artisan - Fatal编程技术网

Php 在Artisan命令中从控制器运行方法?

Php 在Artisan命令中从控制器运行方法?,php,laravel,laravel-artisan,Php,Laravel,Laravel Artisan,在我的自定义Artisan命令中,我从数据库中获取一个项目列表,我希望迭代这些项目,并通过DownloaderController中的方法运行它们。我该怎么做?最好的做法是什么 DownloadCommand.php public function handle() { $files = File::all(); foreach($files as $file) { // downloadFile method b

在我的自定义Artisan命令中,我从数据库中获取一个项目列表,我希望迭代这些项目,并通过DownloaderController中的方法运行它们。我该怎么做?最好的做法是什么

DownloadCommand.php

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

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

    $file->save();
}
DownloadController.php

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

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

    $file->save();
}

控制器中不应包含负责获取数据的逻辑。为此创建一个存储库(或专门的服务),并将其注入到您的命令中。

正确的方法是将该逻辑移动到另一个类,以便它能够从Controller和Comand调用它(控制器和命令显示与应用程序交互的不同方式,但处于同一级别,从另一个调用是错误的)如果下载文件也更新了
$file
记录(检查更新的帖子),那么您将该$file作为参数传递给类方法。如Filesaver::saveFile($file).但数据库更改应该存储在该类中还是存储在控制器中?