PHP code example of laragear / attempt-once

1. Go to this page and download the library: Download laragear/attempt-once 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/ */

    

laragear / attempt-once example snippets


use App\Mails\Newsletter;

attempt_once(function () => {
    Newsletter::send();
});

attempt_once(function () {
    // ... do something.
})

attempt_once(function () {
    // ... do something.
}, now()->addMinute())

$result = attempt_once('send-email')->in(60)->run(function () {
    // ...
});

use App\Enums\EmailType;

$result = attempt_once(EmailType::Transactional)->in(60)->run(function () {
    // ...
});


attempt_once('send-email')->run(function () {
    // ...
});

// "send-email|transaction|user:1"
attempt_once('send-email', 'transaction', ['user' => 1])->run(function () {
    // ...
});

use App\Models\User;

$user = User::find(1);

// "send-email|\App\Models\User:1"
attempt_once('send-email', $user)->run(function () {
    // ...
});

use App\Models\User;
use App\Enums\EmailType;

$user = User::find(1);

// "send-email|\App\Enums\EmailType:Transactional|\App\Models\User:1"
attempt_once('send-email', EmailType::Transactional)->run(function () {
    // ...
});

use function Illuminate\Support\seconds;

// Using seconds
attempt_once('send-email')->for(30)->run(function () {
    // ...
});

// Using a DateTimeInterface, like a Carbon instance
attempt_once('send-email')->for(now()->addSeconds(30))->run(function () {
    // ...
});

// Using a DateInterval, like the `seconds()` helper.
attempt_once('send-email')->for(seconds(30))->run(function () {
    // ...
});

use App\Models\Article;
use Illuminate\Support\Facades\Route;

Route::get('/articles/all', function () {
    $articles = attempt_once(function () {
        return Article::limit(10)->latest()->get();
    });
    
    // Check the callback was not executed
    if ($articles === false) {
        return 'You need to wait 30 seconds to retrieve more articles';
    }
    
    return $articles;
});

use App\Models\Article;
use function Illuminate\Support\minutes;

$collection = attempt_once('latest-articles')
    ->or(new Collection())
    ->run(function () {
        return Article::limit(10)->latest()->get();
    });

if (attempt_once('send-email')->wasExecuted()) {
    return 'An email was already sent!';
}

if (attempt_once('send-email')->wasNotExecuted()) {
    return 'You can send a new email now';
}

$seconds = attempt_once('send-email')->availableIn();

echo "You can send a new email in $seconds seconds.";

$datetime = attempt_once('send-email')->readyAt();
 
echo "You can send a new email at $datetime."