PHP code example of mateffy / laravel-job-progress

1. Go to this page and download the library: Download mateffy/laravel-job-progress library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mateffy / laravel-job-progress example snippets


use Mateffy\JobProgress\Contracts\HasJobProgress;
use Mateffy\JobProgress\Traits\Progress;

class MyJob implements ShouldQueue, HasJobProgress
{
    use Queueable;
    use Progress;

    /** 
     * Return a unique ID for this job instance, 
     * using which you can access progress outside the job 
     */
    public function getProgressId(): string {}

    /** 
     * Implement your job handler here.
     */
    public function handleWithProgress(): void {}
}

public function handleWithProgress(): void
{
    $request = Http::get('...');
    
    // If the job failed, simply throw an exception.
    // The job status will be updated as `failed` accordingly.
    if ($request->failed()) {
        throw new Exception('Request failed');
    }
    
    $this->progress()->update(0.5); // Set progress to 50%
    
    $saved = MyModel::createFromData($request->json());
    
    // Progress is completed automatically when the job finished.
    // Optionally, if you want to associate some piece of data (for example the saved model) to work with later,
    // you can manually mark the progress as completed too.
    $this->progress()->complete(result: $saved);
}

public function handleWithProgress(): void
{
    $articles = News::recent();
    
    $this->progress()->update(0.25); // Set progress to 50%
    
    foreach ($articles as $index => $item) {
    	News::postToSocialMedia($item);
    	
    	$this->progress()->updateWithSteps(
    	    completed: $index + 1,
    	    total: count($articles),
    	    base: 0.25, // continue the progress at 25% (which is what we set after data fetching)
    	    max: 0.5, // this part of the job can "take up" 50% of the total progress
    	)
    }
    
    // Progress is now at 75%
    
    News::sendNewsletter();
}

$this->progress()->complete();

// With some data attached:
$this->progress()->complete(result: $result);

// Mark as failed by throwing an exception inside the job:
throw new Exception('This will automatically mark the job as failed');

// If doing soething custom or from outside the job:
$this->progress()->fail(error: 'Something went wrong');

use \Mateffy\JobProgress\Data\JobState;

$id = uniqid();
MyJob::dispatch(id: $id);

/** @var ?JobState $state */
$state = MyJob::getProgress($id);
$state->progress; // float
$state->status; // JobStatus enum
$state->result; // mixed, your own custom result data
$state->error; // ?string, error message if the job failed

if (MyJob::lock($id)) {
    MyJob::dispatch($id, ...);
}

#[Cancellable]
class MyJob implements ShouldQueue, HasJobProgress
{
    // ...
    
    public function handleWithProgress(): void
    {
        $articles = News::recent();
        $comments = [];
        
        foreach ($articles as $index => $article) {
            // Check if the job was cancelled, and exit if so
            $this->progress()
                ->updateWithSteps(completed: $index + 1, total: count($articles), max: 0.5)
                ->exitIfCancelled(); 
           
            $comments = [...$articles, ...News::comments($article)];
        }
        
        // Check for cancellation one last time, as the job may have been cancelled after the last iteration
        $this->progress()
            ->update(0.5)
            ->exitIfCancelled();
        
        // Now that we're persisting data, we no longer 

/** @var \Mateffy\JobProgress\Data\JobState $state */
$state = MyJob::getProgress($id);
$state->cancel();

// Mark job as uncancellable if progress >= 75%
#[Cancellable(threshold: 0.75)]
class MyJob extends Job implements Progressable
{
    use Progress;
    // ...
}

// Example using a reproducible ID and a Livewire component
use Mateffy\JobProgress\Contracts\HasJobProgress;
use Mateffy\JobProgress\Traits\Progress;
use App\Models\Product;

class ReproducibleIDJob implements ShouldQueue, HasJobProgress
{
    public function __construct(protected Product $product) {}
    
    public function getProgressId(): string 
    {
        return $this->product->id;
    }
}

class MyLivewire extends Component
{
    #[Locked]
    public Product $product;
    
    #[Computed]
    public function progress()
    {
        return UniqueIDJob::getProgress($this->product->id);
    }
    
    public function dispatchMyJob()
    {
        UniqueIDJob::dispatch(product: $this->product);
    }
}

// Example using a random ID and a Livewire component
use Mateffy\JobProgress\Contracts\HasJobProgress;
use Mateffy\JobProgress\Traits\Progress;

class UniqueIDJob implements ShouldQueue, HasJobProgress
{
    public function __construct(protected string $id) {}
    
    public function getProgressId(): string 
    {
        return $this->id;
    }
}

class MyLivewire extends Component
{
    #[Locked]
    public string $id;
    
    #[Computed]
    public function progress()
    {
        return UniqueIDJob::getProgress($this->id);
    }
    
    public function dispatchMyJob()
    {
        // Dispatch the job
        $this->id = uniqid();
        
        UniqueIDJob::dispatch(id: $this->id);
    }
}