Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Stringable Laravel Package

hyperf/stringable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require hyperf/stringable
    

    No configuration or service provider registration is needed—it works as a standalone utility.

  2. 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();
    
  3. Where to Look First:

    • Core Methods: Focus on Str::of(), ->upper(), ->lower(), ->slug(), ->contains(), and ->replace().
    • Documentation: Refer to Laravel’s Stringable docs (90%+ identical).
    • Source Code: Stringable.php for edge cases.

Implementation Patterns

Core Workflows

  1. Immutable Chaining:

    $slug = Str::of($title)
        ->lower()
        ->replace([' ', '_'], '-')
        ->trim();
    
  2. Validation & Sanitization:

    if (Str::of($input)->contains('admin')) {
        throw new \InvalidArgumentException('Forbidden keyword');
    }
    
  3. Localization Helpers:

    $plural = Str::of($count)
        ->plural('item', 'items'); // "1 item", "5 items"
    
  4. API Response Formatting:

    $response = Str::of($error)
        ->explode("\n")
        ->map(fn($line) => "• $line")
        ->implode("\n");
    

Integration Tips

  • 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());
    

Gotchas and Tips

Pitfalls

  1. Method Signature Differences:

    • Some methods (e.g., ->replaceFirst()) may have different parameter orders than Laravel’s version. Always check the source.
  2. Unicode Handling:

    • Not all methods (e.g., ->slug()) are Unicode-aware by default. Use ->ascii() or ->transliterate() for non-ASCII strings:
      Str::of('café')->slug(); // "cafe" (ASCII fallback)
      
  3. Performance in Loops:

    • Avoid creating 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();
      }
      
  4. Hyperf-Specific Quirks:

    • If used in Hyperf’s coroutine context, ensure no blocking operations (e.g., ->contains() with regex) that could stall the event loop.

Debugging Tips

  • 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()]);
    

Extension Points

  1. Custom Macros: Add project-specific methods globally:

    Str::macro('truncateWords', function($limit) {
        return $this->words()->slice(0, $limit)->implode(' ');
    });
    
  2. Override Default Behavior: Replace the entire Stringable class in the service container:

    $container->bind(Stringable::class, CustomStringable::class);
    
  3. 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());
    

Configuration Quirks

  • No Config File: The package is zero-config. All behavior is method-driven.
  • Locale Settings: For pluralization or transliteration, ensure your app’s locale is set (e.g., app()->setLocale('en')).

Pro Tips

  • 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
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor