hyperf/stdlib
Hyperc/stdlib provides foundational utilities for the Hyperf ecosystem: common helpers, collections, array and string tools, and lightweight polyfills used across components. A small, reusable standard library for building high-performance PHP apps and services.
Installation:
composer require hyperf/stdlib
Ensure your composer.json specifies a compatible version (e.g., "hyperf/stdlib": "^3.1").
First Use Case:
Replace a custom array helper with Arr:
use Hyperf\Stdlib\Arr;
$config = ['database' => ['host' => 'localhost', 'port' => 3306]];
$host = Arr::get($config, 'database.host'); // Returns 'localhost'
Where to Look First:
Hyperf\Stdlib namespace for Arr, Str, Collection, Json, etc.Quick Wins:
array_merge_recursive with Arr::deepMerge().Collection::make() for fluent array operations (e.g., filtering, mapping).Str::camel() or Str::snake() for naming conventions.Data Transformation Pipelines:
Chain Collection methods for API responses or event payloads:
use Hyperf\Stdlib\Collection;
$response = Collection::make($data)
->filter(fn($item) => $item['active'])
->pluck('name')
->toArray();
Validation Logic:
Use Arr for nested input sanitization:
use Hyperf\Stdlib\Arr;
$cleanInput = Arr::only($request->all(), ['user', 'metadata']);
Shared Utility Layer:
Json::prettyPrint() for debug logs.Arr::dot() to flatten config keys for Redis.Str::headline().Hyperf-Specific Integrations:
Collection::async() for batch processing:
$results = Collection::make($tasks)
->async(fn($task) => $this->processTask($task))
->all();
hyperf/stdlib helpers:
$container->bind('app.helpers', fn() => new class {
public function __call($method, $args) {
return Arr::$method(...$args);
}
});
Configuration Management:
Merge configs across services with Arr::deepMerge():
$mergedConfig = Arr::deepMerge(
require __DIR__.'/config/base.php',
require __DIR__.'/config/override.php'
);
Migrating Custom Helpers:
array_column() with Collection::pluck().Arr::get() instead of isset($array[$key]).Str::* for string manipulations (e.g., Str::limit()).Testing Utilities:
hyperf/stdlib helpers in PHPUnit:
$this->partialMock(Arr::class, ['get'])->shouldReceive('get')->andReturn($mockData);
Performance Optimization:
Collection vs. native PHP for large datasets:
$collection = Collection::make(range(1, 100000));
$collection->sum(); // Compare with array_sum()
hyperf/stdlib helpers as singletons in config/autoload.php:
'dependencies' => [
Arr::class => Hyperf\Stdlib\Arr::class,
],
HelperService class to wrap hyperf/stdlib with custom logic:
class HelperService {
public function transformUserData(array $data): array {
return Arr::only(Collection::make($data)->toArray(), ['id', 'name']);
}
}
foreach over Collection::each() for tiny arrays).Hyperf-Specific Assumptions:
Collection::async() requires Hyperf’s go functions.Namespace Collisions:
Arr, Str, etc., to prevent autoloading conflicts.Immutable Collections:
Collection::* methods return new collections; original data is unchanged:
$data = [1, 2, 3];
$filtered = Collection::make($data)->filter(fn($x) => $x > 1);
// $data remains [1, 2, 3]
Performance Overhead:
Collection adds minor overhead for small arrays. Benchmark before use:
// Slow for tiny arrays:
Collection::make([1, 2])->sum();
// Faster:
array_sum([1, 2]);
Deprecated Methods:
Arr::setValue() → Arr::set()).Enable Strict Typing:
Use declare(strict_types=1) to catch type mismatches in helper methods.
Log Helper Calls:
Wrap hyperf/stdlib calls in a debug layer:
if (app()->environment('local')) {
Arr::macro('debugGet', function ($array, $key) {
logger()->debug("Arr::get($key)", ['array' => $array]);
return Arr::get($array, $key);
});
}
Check for Coroutine Leaks:
Ensure async helpers (e.g., Collection::async()) are awaited:
$results = yield Collection::make($tasks)->async(fn($task) => $task());
Autoloading:
Ensure composer dump-autoload is run after installation.
Custom Helpers:
Extend hyperf/stdlib by publishing macros:
Arr::macro('customMerge', function ($array1, $array2) {
return Arr::deepMerge($array1, $array2);
});
Environment-Specific Behavior:
Override helpers in config/autoload.php:
'stdlib' => [
'default_locale' => env('APP_LOCALE', 'en_US'),
],
Create Custom Collections:
Extend Hyperf\Stdlib\Collection:
class UserCollection extends Collection {
public function activeOnly(): self {
return $this->filter(fn($user) => $user['active']);
}
}
Add Global Helpers: Register macros in a service provider:
public function boot(): void {
Arr::macro('path', function ($array, $path) {
return Arr::get($array, $path);
});
}
Integrate with Hyperf Components:
Arr in hyperf/validation rules:
$validator->rule('required', Arr::get($data, 'user.name'));
Arr::only():
public function handle($request, Closure $next) {
$cleanData = Arr::only($request->all(), ['id', 'name']);
$request->merge($cleanData);
return $next($request);
}
Collection::when() for Conditional Logic:
$collection = Collection::make($items)
->when($flag, fn($c) => $c->filter(fn($item) => $item['active']))
->pluck('id');
Arr::dot() for Config:
Flatten nested configs for Redis or env vars:
$flatConfig = Arr::dot(['db' => ['host' => 'localhost']]);
// Returns 'db.host=localhost'
make:
Generate utility classes dynamically:
$helper = app()->makeWith(Hyperf\Stdlib\Arr::class, ['config']);
How can I help you explore Laravel packages today?