我正在开发一个从CSV文件导入邮件列表的系统。为此,我正在使用Eloquent ORM在我的模型Target
中的以下代码中将所有电子邮件从CSV导入数据库:
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();
}
}
导入整个CSV文件通常需要很长时间,我想在后台运行此过程。我知道有几个工具可以做到这一点,比如shell_exec()
、the operator & in the end
、crontab
等......
但我什至不知道如何在命令行 Scope 中使用 Eloquent ORM。使用php script_that_imports.php
不起作用,因为有许多依赖项仅适用于Laravel框架
关于如何运行后台代码但仍使用框架工具的任何想法?
您可以使用事件或队列。如果该过程耗时/资源,我想最好使用队列 http://four.laravel.com/docs/queues。
Queue::push('ImportCsv', array('file' => $path_to_file));
并在适当的处理程序类中处理它
class ImportCsv {
public function fire($job, $data)
{
//do your stuff here
$job->delete(); //remove job from queue after completion
}
}
要使上述工作正常工作,请记住运行队列列表器
php artisan queue:listen
编辑:抱歉,我没有注意到您正在单独询问CLI范围 - 您能否提供更多细节,因为不清楚您要实现什么?上述解决方案适用于基于 Web 的 php 执行。您可以在后台进行队列处理,而不仅限于在一个请求期间运行处理 - 这将"阻止"您在处理期间执行进一步的操作。但我不确定这是否是你想要的?