Topics

Jobs

A job is a task that can be shared across plugins. You might have many plugins listening to the same job, but after first plugin claims the job has been processed, others will not be notified. This is the main difference compare to events and filters.

Jobs are commonly used for actions that can be overriden by other plugins. E.g. ImpressPages has ipFormatPrice function. This function throws ipFormatPrice job and if there is at least one plugin which returns formatted date using a job, system uses its job method instead of default ipFormatPrice function implementation. That means if you catch ipFormatPrice job and return not null value, you will ocmpletely override default functionality. 

When performing a job, job listener executes a callable function from a Job class, placed in Job.php file. This function name is a job name. To organize jobs easier, it is recommended to prefix your job names with a plugin name, e.g. MyPlugin_Myjob.

Adding a job listener

To catch jobs, add Job.php file with Job class to your plugin's root directory. Each method of this class should match job name you want to process.

The sample code below adds a listener, which waits for a job named ipFormatDate.

<?php
namespace Plugin\MyPlugin;

class Job
{
    public static function ipFormatDate($data)
    {
          return ('Y-m-d', $data['timestamp']);
    }
}

Setting job listener's priority

If the same job has more than one job listener, then the job is handled only by a listener which has a highest priority. Job's priority is set by specifying a numeric value, which follows a function name and underscore character. The lower the number the higher the priority. The default priority value is set to 50.

Set job listener's priority

<?php
public function ipFormatDate_10($data) 
{
    // ...
}

Creating your own job

<?php
$data = array('myString' => 'MY SAMPLE TEXT'); //any data that might be needed to process the job
ipJob('changeToLowerCase', $data);

This is how you can catch this job in the same or other plugin:

<?php
namespace Plugin\MyPlugin;

class Job
{
    public static function changeToLowerCase($data)
    {
          strtolower ($data['myString']);
    }
}

See also

comments powered by Disqus