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?
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?