Please mention somewhere that construction parameters should not be declared on Job class
axyr opened this issue · 4 comments
Took me a while before I figured out that this does not work :
class SendEmailJob extends AbstractQueuedJob {
public $to = ''; // don't do this
private $subject = ''; // don't do this either
public function __construct($to = 'info@example.org', $subject = 'Queued Email') {
$this->to = $to; // just do this
$this->subject = $subject; //and this
$this->currentStep = 0;
$this->totalSteps = 1;
}
}
It does, but yes, it should be made clearer that if you do want to use constructor arguments,
a) they must have default parameters, as the JobService will re-create the job class passing through no constructor params
b) you must have logic in your constructor that can determine if it's been constructed by the job service, or by user-land code, and whether the constructor params are to be used.
The kind of logic to use in your constructor could be something like
public function __construct($to = null) {
if ($to) {
// we know that we've been called by user code, so
// do the real initialisation work
}
}
Of course, the other alternative is to set properties on the job directly after constructing it from your own code.
Actually, this was mentioned in the wiki, but I've made it a bit clearer, and referenced it from the README file
@nyeholt thanks for somewhat clarifying this, but where exactly can I put the parameters passed in to the constructor of the job in order to persist / make this information available to the running of it across multiple steps?
For example public function __construct($startDate = null, $endDate = null). I want the start and end dates available in the process() function.
Is there something built in to the queued jobs to do this, or will I have to think up my own way of storing the parameters (in DB or file) and then loading them back in the setup() function?
Any guidance you can give on this would be greatly appreciated.
Thanks.
I've made it a little clearer in the wiki page, and copy / pasted below
Job Properties QueuedJobs inherited from the AbstractQueuedJob have a default mechanism for persisting values via the __set and __get mechanism that stores items in the jobData map, which is serialize()d between executions of the job processing. All you need to do from within your job is call $this->myProperty = 'somevalue';
, and it will be automatically persisted for you; HOWEVER, on subsequent creation of the job object (ie, in the __constructor()
) these properties have not been loaded, so you cannot rely on them at that point.