Download the PHP package yannelli/attempt without Composer

On this page you can find all versions of the php package yannelli/attempt. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package attempt

Attempt

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Introduction

While building your application, you may encounter operations that can fail due to transient issues like network timeouts, API rate limits, or temporary service unavailability. Rather than letting these failures crash your application or writing repetitive try-catch blocks, Laravel Attempt provides a fluent, composable system for handling retries, fallbacks, and error recovery.

Attempt treats error handling as a first-class pipeline concern, allowing you to declaratively define how your application should respond when things go wrong. Whether you need simple retry logic with exponential backoff, complex fallback chains, or integration with Laravel’s native Pipeline, Attempt provides an expressive API that reads like natural language.

Installation

Attempt supports PHP 8.4 or newer and Laravel 12 or 13.

You may install Attempt into your project using the Composer package manager:

After installing Attempt, you may optionally publish its configuration file using the vendor:publish Artisan command:

Making Attempts

Basic Usage

The simplest way to use Attempt is to wrap a potentially failing operation with the try method. To execute the attempt and retrieve the result, you may call the thenReturn method:

If you need to pass input to your callable, you may provide additional arguments to the try method:

You may also pass an array of callables to the try method. When an array is provided, each callable will be executed in order as a fallback chain. If the first callable fails, the second will be attempted, and so on:

Attempt provides several methods for executing your attempt and retrieving the result:

Method Behavior
then(Closure $callback) Transform and return the final result
thenReturn() Return the processed value directly
thenReturnOrFail() Return the value or throw on failure
run() Return an AttemptResult object with metadata
get() Alias for thenReturn()
value() Alias for thenReturn()

Attemptable Classes

For more complex operations, you may create dedicated attemptable classes. These classes should implement the Attemptable interface and define a handle method that receives the input and returns a result:

Once you have defined your attemptable class, you may pass its class name to the try method:

Self-Configuring Classes

Sometimes you may want a class to define its own retry and fallback configuration. To accomplish this, your class may implement both the Attemptable and ConfiguresAttempt interfaces. The configureAttempt method receives an AttemptBuilder instance that you may use to define your preferred configuration:

When using a self-configuring class, the configuration is automatically applied:

Retry Configuration

Specifying Retry Attempts

By default, Attempt will not retry a failed operation. To enable retries, call the retry method and specify how many retries are allowed in addition to the initial attempt. For example, retry(3) permits up to four total executions:

Delay Strategies

Often, you will want to wait between retry attempts to give transient issues time to resolve. Attempt provides several strategies for configuring delays between retries.

Fixed Delay

To wait a fixed number of milliseconds between all retries, pass an integer to the delay method:

Explicit Delays

If you need different delays for each retry attempt, you may pass an array of millisecond values:

Exponential Backoff

Exponential backoff progressively increases the delay between retries. This strategy is particularly useful when interacting with rate-limited APIs or overloaded services. The exponentialBackoff method accepts a base delay and an optional maximum delay:

Linear Backoff

Linear backoff increases the delay by a fixed increment with each retry:

Adding Jitter

To prevent multiple failing operations from retrying in lockstep (known as the “thundering herd” problem), you may add randomized jitter to your delays. The withJitter method accepts a percentage value that determines how much variance to apply:

Custom Delay Functions

For complete control over delay calculation, you may use the delayUsing method with a closure that receives the current attempt number and the exception that triggered the retry:

Conditional Retries

Sometimes you may only want to retry an operation for specific types of failures. The retryIf method accepts a closure that receives the thrown exception and returns a boolean indicating whether the operation should be retried:

Fallback Handlers

Defining Fallbacks

When an operation fails after exhausting all retries, you may want to execute a fallback operation instead of throwing an exception. Use the fallback method to define an alternative callable:

Fallback Chains

You may define multiple fallbacks that will be tried in order. The first successful fallback wins:

For a more expressive syntax, you may chain multiple orFallback calls:

The Fallbackable Interface

For fallback classes that need access to the original exception, implement the Fallbackable interface. This interface defines a handleFallback method that receives both the exception and the original input:

Exception Handling

Catching Exceptions

Attempt allows you to register exception handlers that will be invoked when specific exceptions occur. You may catch specific exception types or all exceptions:

Re-throwing Exceptions

If you want to execute a handler but still throw the exception afterward, chain the throw method:

Suppressing Exceptions

To suppress all exceptions and return null on failure, use the quiet method:

Lifecycle Hooks

Attempt provides several hooks that allow you to execute code at specific points during the attempt lifecycle:

Conditional Execution

You may conditionally execute an attempt using the when and unless methods:

Pipeline Integration

Pipeline Attempts

Attempt integrates seamlessly with Laravel’s Pipeline. Use the pipeline method to execute a series of stages with built-in retry and fallback capabilities:

Using AttemptPipe

You may also use AttemptPipe within a native Laravel Pipeline to wrap individual stages with retry logic:

Concurrent Execution

Running Concurrent Attempts

Use the concurrent method to execute a group of independent attempts and receive an array of results. Attempts currently execute in declaration order in the same process; this API groups results but does not provide parallel execution:

Racing Attempts

Use the race method to try operations in declaration order until one succeeds. Remaining operations are skipped after the first success:

Async Execution

For long-running operations, you may dispatch an attempt to run asynchronously on the queue:

If you need to execute the attempt synchronously instead (bypassing the queue), you may use the await method:

Laravel AI Integration

Attempt provides first-class integration with the official Laravel AI SDK. While the SDK offers provider failover out of the box, it does not retry failed requests. Attempt fills this gap with retry policies tuned specifically for AI workloads, giving you three composable layers of resilience: retry each provider with backoff, fail over across providers, and finally fall back to a cached or canned value.

To get started, install the Laravel AI SDK alongside Attempt:

Retrying AI Requests

The ai method creates an attempt that is pre-configured for AI requests. Only transient failures will be retried: rate limits, provider overloads, connection errors, and retryable HTTP statuses (408, 429, and 5xx). Permanent failures such as insufficient credits, unknown tools, invalid requests, and malformed responses fail immediately:

When a provider supplies a Retry-After header with a rate limit response, Attempt will honor it (capped at 30 seconds). Otherwise, delays are calculated using decorrelated jitter starting at 500 milliseconds. You may override the delay behavior using any of the standard delay methods:

Because ai returns a standard attempt builder, the full Attempt API remains available. For example, you may combine AI retries with the SDK's provider failover and a non-AI fallback:

The ai method works equally well for the SDK's other operations, such as image generation and embeddings, since they throw the same transient exception types:

If you need to customize retry classification, the underlying policy is exposed as Yannelli\Attempt\Ai\AiRetryPolicy, and the standard retryIf method may be used to replace it entirely.

Per-Provider Retries with Agent Middleware

The SDK's provider failover moves to the next provider on the first failure. If you would rather retry each provider before failing over, add the RetryAiRequests middleware to your agent. Since agent middleware runs once per provider in the failover list, each provider will be retried independently:

After exhausting its retries, the middleware re-throws the original exception so the SDK's failover proceeds normally. You may customize the underlying attempt using the configureUsing method:

Retry Safety

A few caveats apply when retrying AI operations:

Working with Results

The AttemptResult Object

When you call the run method instead of thenReturn, you receive an AttemptResult object that provides detailed information about the attempt:

Monadic Operations

The AttemptResult object supports monadic operations for functional-style programming:

Events

Attempt dispatches events throughout the attempt lifecycle, allowing you to hook into various stages for logging, monitoring, or other purposes:

Event When Fired
AttemptStarted When the attempt begins
AttemptSucceeded On successful completion
AttemptFailed On each failure (before retry)
RetryAttempted When a retry is initiated
FallbackTriggered When a fallback is tried
AllAttemptsFailed When all attempts and fallbacks fail

If you need to disable events for a specific attempt, use the withoutEvents method:

Testing

Attempt includes a convenient fake implementation for testing. Use the fake method to replace the Attempt facade with a test double:

To run the package’s test suite:

Configuration

The published configuration file (config/attempt.php) allows you to customize named backoff strategies, queue behavior, events, and global exception retry rules:

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.


All versions of attempt with dependencies

PHP Build Version
Package Version
Requires php Version ^8.4
illuminate/bus Version ^12.0 || ^13.0
illuminate/contracts Version ^12.0 || ^13.0
illuminate/pipeline Version ^12.0 || ^13.0
illuminate/queue Version ^12.0 || ^13.0
illuminate/support Version ^12.0 || ^13.0
laravel/serializable-closure Version ^2.0
spatie/laravel-package-tools Version ^1.93.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package yannelli/attempt contains the following files

Loading the files please wait ...