programster/runnable

A package for making runnable objects.

1.0.0 2025-07-25 09:19 UTC

This package is auto-updated.

Last update: 2025-07-25 09:25:10 UTC


README

This is a basic package for building runnable objects or background jobs.

Example Usage

Here is an example of creating a "job" that extends the runnable class:

use \Programster\Runnable\Runnable;

class Job extends Runnable
{
    public function __construct(private readonly string $name){}


    public function run() : void
    {
        echo "hello {$this->name}" . PHP_EOL;
    }
}

$job = new Job("Susan");

You can now execute the job by doing any of the following:

// calling the run method.
$job->run();

// invoking it directly.
$job()

// passing it as a callback.
function executor(callable $callback)
{
    $callback();
}

executor($job)

You could even create an executor that takes any number of callbacks and executes them like so:

class JobExecutor() extends Runnable
{
    public function __construct(private readonly callable ...$jobs)
    {
        
    }
    
    
    public function run() : void
    {
        foreach ($this->jobs as $job)
        {
            $job();
        }
    }
}

$executor = new JobExecutor(
    new Job("Tom"),
    new Job("Harry"),
    function() { echo "do something...\n"; },
)

$executor->run();

JSON Serializing Runnable Objects

If you are thinking of storing jobs in a queue that is executed by some background process, then you may wish to use the JsonSerializableRunnable class:

use \Programster\Runnable\JsonSerializableRunnable;

class Job extends JsonSerializableRunnable
{
    public function __construct(private readonly string $name){}


    public function run() : void
    {
        echo "hello {$this->name}" . PHP_EOL;
    }
    
    
    public static function jsonUnserialize(string $jsonForm): static
    {
        $arrayForm = json_decode($jsonForm, true);
        return new Job($arrayForm['name']);
    }


    public function jsonSerialize(): mixed
    {
        return [
            'name' => $this->name,
        ];
    }
}

$job = new Job("Susan");
$jsonForm = json_encode($job->jsonSerialize());
// save to database here...

// retrieve from database and create from the JSON form:
$job = Job::jsonUnserialize($jsonForm);

// execute as normal.
caller($job);