douliang2167 2013-09-07 07:39
浏览 62
已采纳

如何运行后台进程但仍然使用框架设施?

I'm developing a system which imports mailings lists from a CSV file. To accomplish that, I'm using Eloquent ORM to import all e-mails from CSV to Database in the following code in my model Target:

public function importCSV($file)
{
    $destination = 'uploads/';
    $file->move($destination, $file->getClientOriginalName());
    $csv = new parseCSV();
    $csv->auto($destination . $file->getClientOriginalName());

    // There must be a Email field in CSV file
    if(!in_array('Email', $csv->titles))
        throw new Exception("Email field not found", 1);

    foreach($csv->data as $data)
    {
        $this->cont++;
        $mailing = new Mailing();
        $mailing->target()->associate($this);
        $mailing->email = $data['Email'];
        $mailing->save();
    }


}

Importing a whole CSV file usually takes a long time and I'd like to run this process in background. I know that there're a couple of tools which does that like shell_exec(), the operator & in the end, crontab etc...

But I don't even know how I can still use Eloquent ORM in the command line Scope. Using php script_that_imports.php won't work because there're many dependencies which only works inside Laravel framework

Any ideia on how I can run background code but still use the framework facilities?

  • 写回答

1条回答 默认 最新

  • douya1974 2013-09-07 07:45
    关注

    You can use events or queues for that. If the process is time/resource consuming I guess it's best to use queues http://four.laravel.com/docs/queues .

    Queue::push('ImportCsv', array('file' => $path_to_file));
    

    and handle it in an appropirate handler class

    class ImportCsv {
    
        public function fire($job, $data)
        {
            //do your stuff here 
    
            $job->delete(); //remove job from queue after completion
        }
    
    }
    

    For the above to work, remember about running the queue listerener

    php artisan queue:listen
    

    EDIT: sorry, I didn't notice you are asking sepcifically for the CLI scope - can you provide more details, as it is not clear what are you trying to achieve ? The above solution will work for web-based php execution. You can do the queue processing in the background, not limiting yourself to running the processing during one request - which will "block" you from further actions for the time of processing. But I am not sure if it is what you want?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了