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?

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)