PHPackages                             friendsofhyperf/support - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. friendsofhyperf/support

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

friendsofhyperf/support
=======================

Another support component for Hyperf.

v3.1.76(5mo ago)159.1k↑14.8%9MITPHP

Since May 6Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/friendsofhyperf/support)[ Packagist](https://packagist.org/packages/friendsofhyperf/support)[ Fund](https://hdj.me/sponsors/)[ GitHub Sponsors](https://github.com/huangdijia)[ RSS](/packages/friendsofhyperf-support/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (66)Used By (9)

Support
=======

[](#support)

[![Latest Version](https://camo.githubusercontent.com/5b6974462fe61fb15bea5b337115aac9d69b845ce2ced833ae5c7687f0f1c221/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f667269656e64736f666879706572662f737570706f72742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/friendsofhyperf/support)[![Total Downloads](https://camo.githubusercontent.com/b694d7eb2df4bcd7e76e20e8e6424a744ef28c3f7e92c15f82b414895c23a0d5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f667269656e64736f666879706572662f737570706f72742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/friendsofhyperf/support)[![GitHub license](https://camo.githubusercontent.com/d72624db826033160944309858cc5c197ec5bfc897e3d6b6da9a50b4ea49f6ca/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f667269656e64736f666879706572662f737570706f7274)](https://github.com/friendsofhyperf/support)

A comprehensive support component for Hyperf providing essential utilities, helpers, and base classes.

Features
--------

[](#features)

- 🎯 **Fluent Dispatch API** - Elegant job dispatch with support for async queue, AMQP, and Kafka
- 🔄 **Closure Jobs** - Execute closures as background jobs with dependency injection
- 🛠️ **Helper Functions** - Collection of useful helper functions
- 📦 **Bus System** - Pending dispatch classes for various message systems
- 🧩 **Traits &amp; Utilities** - Reusable traits and utility classes
- ⏱️ **Backoff Strategies** - Multiple retry backoff implementations for retry mechanisms

Installation
------------

[](#installation)

```
composer require friendsofhyperf/support
```

Usage
-----

[](#usage)

### Dispatch Helper Function

[](#dispatch-helper-function)

The `dispatch()` helper function provides a fluent API for dispatching jobs to different systems:

#### Async Queue (Closure Jobs)

[](#async-queue-closure-jobs)

```
use function FriendsOfHyperf\Support\dispatch;

// Simple closure dispatch to async queue
dispatch(function () {
    // Your job logic here
    logger()->info('Job executed!');
});

// With configuration
dispatch(function () {
    // Your job logic here
})
    ->onConnection('high-priority')
    ->delay(60) // Execute after 60 seconds
    ->setMaxAttempts(5);

// With dependency injection
dispatch(function (UserService $userService, LoggerInterface $logger) {
    $users = $userService->getActiveUsers();
    $logger->info('Processing ' . count($users) . ' users');
});
```

#### AMQP Producer Messages

[](#amqp-producer-messages)

```
use Hyperf\Amqp\Message\ProducerMessageInterface;
use function FriendsOfHyperf\Support\dispatch;

// Dispatch AMQP message
dispatch($amqpMessage)
    ->setPool('default')
    ->setExchange('my.exchange')
    ->setRoutingKey('my.routing.key')
    ->setTimeout(10)
    ->setConfirm(true);
```

#### Kafka Producer Messages

[](#kafka-producer-messages)

```
use Hyperf\Kafka\Producer\ProduceMessage;
use function FriendsOfHyperf\Support\dispatch;

// Dispatch Kafka message
dispatch($kafkaMessage)
    ->setPool('default');
```

### CallQueuedClosure

[](#callqueuedclosure)

The `CallQueuedClosure` class allows you to execute closures as async queue jobs:

```
use FriendsOfHyperf\Support\CallQueuedClosure;

// Create a closure job
$job = CallQueuedClosure::create(function () {
    // Your job logic
    return 'Job completed!';
});

// Configure max attempts
$job->setMaxAttempts(3);

// The job can be pushed to queue manually or via dispatch()
```

### Pending Dispatch Classes

[](#pending-dispatch-classes)

#### PendingAsyncQueueDispatch

[](#pendingasyncqueuedispatch)

Fluent API for async queue job dispatch:

```
use FriendsOfHyperf\Support\Bus\PendingAsyncQueueDispatch;

$pending = new PendingAsyncQueueDispatch($job);
$pending
    ->onConnection('default')
    ->delay(30)
    ->when($condition, function ($dispatch) {
        $dispatch->onConnection('special');
    })
    ->unless($otherCondition, function ($dispatch) {
        $dispatch->delay(60);
    });
// Job is dispatched when object is destroyed
```

#### PendingAmqpProducerMessageDispatch

[](#pendingamqpproducermessagedispatch)

Fluent API for AMQP message dispatch:

```
use FriendsOfHyperf\Support\Bus\PendingAmqpProducerMessageDispatch;

$pending = new PendingAmqpProducerMessageDispatch($message);
$pending
    ->setPool('default')
    ->setExchange('my.exchange')
    ->setRoutingKey('my.routing.key')
    ->setTimeout(5)
    ->setConfirm(true);
// Message is sent when object is destroyed
```

#### PendingKafkaProducerMessageDispatch

[](#pendingkafkaproducermessagedispatch)

Fluent API for Kafka message dispatch:

```
use FriendsOfHyperf\Support\Bus\PendingKafkaProducerMessageDispatch;

$pending = new PendingKafkaProducerMessageDispatch($message);
$pending->setPool('default');
// Message is sent when object is destroyed
```

### Conditional Execution

[](#conditional-execution)

All pending dispatch classes support conditional execution:

```
use function FriendsOfHyperf\Support\dispatch;

dispatch($job)
    ->when($shouldUseHighPriority, function ($dispatch) {
        $dispatch->onConnection('high-priority');
    })
    ->unless($isTestMode, function ($dispatch) {
        $dispatch->delay(10);
    });
```

API Reference
-------------

[](#api-reference)

### dispatch($job)

[](#dispatchjob)

Creates a pending dispatch instance based on the job type:

- `Closure` → `PendingAsyncQueueDispatch` with `CallQueuedClosure`
- `ProducerMessageInterface` → `PendingAmqpProducerMessageDispatch`
- `ProduceMessage` → `PendingKafkaProducerMessageDispatch`
- Other objects → `PendingAsyncQueueDispatch`

### PendingAsyncQueueDispatch Methods

[](#pendingasyncqueuedispatch-methods)

- `onConnection(string $connection): static` - Set queue connection
- `delay(int $delay): static` - Delay job execution (seconds)
- `setMaxAttempts(int $attempts): static` - Set max retry attempts
- `when(mixed $condition, callable $callback): static` - Conditional execution
- `unless(mixed $condition, callable $callback): static` - Inverse conditional execution

### PendingAmqpProducerMessageDispatch Methods

[](#pendingamqpproducermessagedispatch-methods)

- `setPool(string $pool): static` - Set AMQP pool name
- `setExchange(string $exchange): static` - Set exchange name
- `setRoutingKey(array|string $routingKey): static` - Set routing key(s)
- `setTimeout(int $timeout): static` - Set timeout (seconds)
- `setConfirm(bool $confirm): static` - Enable/disable confirm mode
- `when(mixed $condition, callable $callback): static` - Conditional execution
- `unless(mixed $condition, callable $callback): static` - Inverse conditional execution

### PendingKafkaProducerMessageDispatch Methods

[](#pendingkafkaproducermessagedispatch-methods)

- `setPool(string $pool): static` - Set Kafka pool name
- `when(mixed $condition, callable $callback): static` - Conditional execution
- `unless(mixed $condition, callable $callback): static` - Inverse conditional execution

### CallQueuedClosure

[](#callqueuedclosure-1)

- `create(Closure $closure): static` - Create a new closure job
- `setMaxAttempts(int $attempts): void` - Set max retry attempts
- `handle(): mixed` - Execute the closure (called by queue worker)

### Backoff Strategies

[](#backoff-strategies)

The component provides various backoff strategies for retry mechanisms:

#### ArrayBackoff

[](#arraybackoff)

Use custom delay intervals defined in an array:

```
use FriendsOfHyperf\Support\Backoff\ArrayBackoff;

// Custom delays
$backoff = new ArrayBackoff([100, 500, 1000, 2000, 5000]);

// Stop after array is exhausted (returns 0)
$backoff = new ArrayBackoff([100, 500, 1000], false);

// From comma-separated string
$backoff = ArrayBackoff::fromString('100, 500, 1000, 2000');

// From predefined patterns
$backoff = ArrayBackoff::fromPattern('short');      // [100, 200, 300, 500, 1000]
$backoff = ArrayBackoff::fromPattern('medium');     // [200, 500, 1000, 2000, 5000]
$backoff = ArrayBackoff::fromPattern('long');       // [500, 1000, 2000, 5000, 10000, 30000]
$backoff = ArrayBackoff::fromPattern('exponential'); // [100, 200, 400, 800, 1600, 3200, 6400]

// Usage in retry logic
$attempt = 0;
while (true) {
    try {
        return performOperation();
    } catch (Exception $e) {
        $delay = $backoff->next();
        if ($delay === 0) {
            throw $e; // No more retries
        }
        usleep($delay * 1000); // Convert to microseconds
    }
}
```

#### Available Backoff Implementations

[](#available-backoff-implementations)

- **ArrayBackoff** - Custom intervals from an array
- **FixedBackoff** - Constant delay between retries
- **LinearBackoff** - Linear growth with configurable step
- **ExponentialBackoff** - Exponential growth with optional jitter
- **FibonacciBackoff** - Fibonacci sequence-based delays
- **PoissonBackoff** - Statistical distribution-based delays
- **DecorrelatedJitterBackoff** - Decorrelated jitter for better spreading

#### Common Backoff Interface

[](#common-backoff-interface)

All backoff implementations implement `BackoffInterface`:

```
interface BackoffInterface
{
    public function next(): int;           // Get next delay in milliseconds
    public function reset(): void;         // Reset attempt counter
    public function getAttempt(): int;     // Get current attempt count
    public function sleep(): int;          // Sleep for calculated delay
}
```

Contact
-------

[](#contact)

- [Twitter](https://twitter.com/huangdijia)
- [Gmail](mailto:huangdijia@gmail.com)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance72

Regular maintenance activity

Popularity32

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~15 days

Recently: every ~2 days

Total

65

Last Release

163d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/8337659?v=4)[Deeka Wong](/maintainers/huangdijia)[@huangdijia](https://github.com/huangdijia)

---

Top Contributors

[![huangdijia](https://avatars.githubusercontent.com/u/8337659?v=4)](https://github.com/huangdijia "huangdijia (76 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (2 commits)")[![xuanyanwow](https://avatars.githubusercontent.com/u/28777109?v=4)](https://github.com/xuanyanwow "xuanyanwow (1 commits)")

---

Tags

hyperfv3.1

### Embed Badge

![Health badge](/badges/friendsofhyperf-support/health.svg)

```
[![Health](https://phpackages.com/badges/friendsofhyperf-support/health.svg)](https://phpackages.com/packages/friendsofhyperf-support)
```

###  Alternatives

[hyperf/crontab

A crontab component for Hyperf.

131.6M62](/packages/hyperf-crontab)[hyperf/di

A DI for Hyperf.

182.8M594](/packages/hyperf-di)[hyperf/validation

hyperf validation

122.1M166](/packages/hyperf-validation)[hyperf/database

A flexible database library.

202.8M257](/packages/hyperf-database)[friendsofhyperf/sentry

The sentry component for Hyperf.

1864.6k](/packages/friendsofhyperf-sentry)[friendsofhyperf/lock

The lock component for Hyperf.

1447.4k](/packages/friendsofhyperf-lock)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
