Installation:
composer require hyperf/stringable
No configuration or service provider registration is needed—it works as a standalone utility.
First Use Case: Replace native string operations with fluent, immutable method chaining:
use Hyperf\Stringable\Str;
$result = Str::of('hello world')
->title() // "Hello World"
->append('!') // "Hello World!"
->slug() // "hello-world"
->toString();
Where to Look First:
Str::of(), ->upper(), ->lower(), ->slug(), ->contains(), and ->replace().Immutable Chaining:
$slug = Str::of($title)
->lower()
->replace([' ', '_'], '-')
->trim();
Validation & Sanitization:
if (Str::of($input)->contains('admin')) {
throw new \InvalidArgumentException('Forbidden keyword');
}
Localization Helpers:
$plural = Str::of($count)
->plural('item', 'items'); // "1 item", "5 items"
API Response Formatting:
$response = Str::of($error)
->explode("\n")
->map(fn($line) => "• $line")
->implode("\n");
Service Container Binding (Optional):
$container->bind(Stringable::class, fn() => new \Hyperf\Stringable\Stringable());
Useful for dependency injection in Hyperf services.
Macros for Custom Logic:
Str::macro('camel', fn($str) => Str::of($str)->camelCase());
Extend functionality without modifying the core package.
Laravel Facade Alias (For Mixed Stacks):
// In a Laravel service provider
Str::macro('hyperf', fn($str) => \Hyperf\Stringable\Str::of($str));
Testing:
Use Str::of() in unit tests for consistent string assertions:
$this->assertEquals('expected', Str::of('input')->slug());
Method Signature Differences:
->replaceFirst()) may have different parameter orders than Laravel’s version. Always check the source.Unicode Handling:
->slug()) are Unicode-aware by default. Use ->ascii() or ->transliterate() for non-ASCII strings:
Str::of('café')->slug(); // "cafe" (ASCII fallback)
Performance in Loops:
Stringable instances in tight loops. Cache the instance or use native PHP strings:
// Bad (creates new instance per iteration)
foreach ($items as $item) {
Str::of($item)->slug();
}
// Good (reuse instance)
$stringable = Str::of('');
foreach ($items as $item) {
$stringable->setString($item)->slug();
}
Hyperf-Specific Quirks:
->contains() with regex) that could stall the event loop.Method Introspection:
Use get_class_methods(\Hyperf\Stringable\Stringable::class) to list all available methods.
Fallback to Native PHP: For unsupported methods, chain to native PHP:
Str::of($str)->toString()->str_replace('old', 'new');
Logging Edge Cases: Log intermediate results for debugging:
$str = Str::of('test');
logger()->debug('Step 1:', ['value' => $str->upper()->toString()]);
Custom Macros: Add project-specific methods globally:
Str::macro('truncateWords', function($limit) {
return $this->words()->slice(0, $limit)->implode(' ');
});
Override Default Behavior:
Replace the entire Stringable class in the service container:
$container->bind(Stringable::class, CustomStringable::class);
Hybrid Usage with Laravel: In a Laravel/Hyperf hybrid app, alias methods to avoid conflicts:
Str::macro('hyperfSlug', fn($str) => \Hyperf\Stringable\Str::of($str)->slug());
app()->setLocale('en')).Use ->toString() Explicitly:
Always call ->toString() to convert back to a native string to avoid confusion in logs or DB queries.
Combine with Collections:
Leverage Laravel’s Collection methods with Stringable:
collect($titles)->map(fn($title) => Str::of($title)->slug());
Performance Benchmarking: For critical paths, compare against native PHP:
$time = microtime(true);
Str::of(str_repeat('a', 1000))->reverse();
echo microtime(true) - $time; // ~0.0001s
How can I help you explore Laravel packages today?