1. Go to this page and download the library: Download slashequip/attempt 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/ */
slashequip / attempt example snippets
use SlashEquip\Attempt\Attempt;
$attempt = new Attempt();
$attempt = Attempt::make();
$attempt
->try(function () {
// My code that may or may not work.
})
->thenReturn();
// $valueOne will be true
$valueOne = $attempt
->try(function () {
return true;
})
->thenReturn();
// $valueTwo will be false
$valueTwo = $attempt
->try(function () {
return true;
})
->then(function ($result) {
return !$result;
});
// $valueThree will be true
$valueThree = $attempt
->try(function () {
return true;
})();
$valueOne = $attempt
->try(function () {
throw new RuntimeException();
})
->times(5)
->thenReturn();
// The above code would be run 5 times before throwing the RuntimeException
$attempt
->try(function () {
throw new UnexpectedException;
})
->catch(TheExceptionWeAreExpecting::class)
->catch(AnotherExceptionWeAreExpecting::class)
->thenReturn();
// In this example; only one attempt would be made and a UnexpectedException would be thrown
$attempt
->try(function () {
throw new AnExpectedException;
})
->catch(AnExpectedException::class, function (AnExpectedException $e) {
error_log($e->getMessage());
return new NullBlogPost();
})
->thenReturn();
$attempt
->try(function () {
throw new RuntimeException();
})
->noThrow()
->thenReturn();
// The above exception would not bubble up and instead, simply, be swallowed.
$attempt
->try(function () {
throw new UnexpectedException;
})
->finally(function () {
// run some clean up.
})
->thenReturn();
// In this example; the finally callback would be run before the UnexpectedException is thrown
$attempt
->try(function () use ($data) {
throw new UnexpectedException;
})
->times(3)
->waitBetween(250)
->thenReturn();
// In this example, there would be a pause of 250 milliseconds between each attempt.
use SlashEquip\Attempt\Attempt;
use GuzzleHttp\Exception\ClientException;
$blogPost = Attempt::make()
->try(function () use ($data) {
return UnstableBlogApiServiceUsingGuzzle::post([
'data' => $data,
]);
})
->times(3)
->waitBetween(250)
->catch(ClientException::class, function (ClientException $e) {
error_log("Unstable blog api service is causing issues again.")
return new BlogPost::nullableObject();
})
->then(function ($apiResponse) {
return BlogPost::fromApiResponse($apiResponse);
});
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.