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

Str Laravel Package

php-standard-library/str

Lightweight string utility library for PHP, providing common helpers for formatting, parsing, and safe string handling. Designed as a simple “standard library” add-on with a small API surface and easy composer integration.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require php-standard-library/str
    

    No configuration required—just autoload via Composer.

  2. First Use Case: Replace native PHP string functions with clearer, more expressive helpers. For example:

    use Str\Str;
    
    $text = Str::of('  Hello World  ')
        ->trim()
        ->lower()
        ->replace(' ', '-')
        ->value(); // Returns 'hello-world'
    
  3. Where to Look First:

    • Core Methods: Focus on Str::of() (fluent interface) and static helpers like Str::slug(), Str::title(), or Str::ascii().
    • Documentation: Check the src/Str namespace for method signatures and examples. No external docs needed—code is self-documenting.

Implementation Patterns

Fluent vs. Static Usage

  • Fluent Chain (OOP-style):

    $cleaned = Str::of($userInput)
        ->trim()
        ->slug()
        ->prepend('post-')
        ->value();
    

    Use when: Transforming strings in a single operation with intermediate steps.

  • Static Helpers (Procedural-style):

    $title = Str::title('hello world'); // "Hello World"
    $slug = Str::slug('Laravel News');   // "laravel-news"
    

    Use when: One-off transformations or in non-OOP contexts (e.g., Blade templates).

Common Workflows

  1. Input Sanitization:

    $safeInput = Str::of(request('name'))
        ->trim()
        ->ascii()
        ->value();
    

    Why: Combines trimming, ASCII conversion, and safety in one chain.

  2. URL/Slug Generation:

    $slug = Str::of($postTitle)
        ->slug()
        ->lower()
        ->value();
    

    Tip: Chain with Str::kebab() for alternative separators.

  3. Text Wrapping:

    $wrapped = Str::of($longText)
        ->wrap(80, "\n")
        ->value();
    

    Use case: Preparing CLI output or formatted emails.

  4. Case Conversion:

    $snakeCase = Str::of('HelloWorld')
        ->snake()
        ->value(); // "hello_world"
    

    Pair with: Laravel’s snake_case conventions for consistency.

Integration with Laravel

  • Service Providers: Bind Str as a singleton for global access:

    $this->app->singleton('str', fn() => new Str\Str());
    

    Then inject via constructor:

    public function __construct(private Str\Str $str) {}
    
  • Blade Directives: Create a custom Blade helper:

    Blade::directive('str', function ($expression) {
        return "<?php echo app('str')->of({$expression})->value(); ?>";
    });
    

    Usage:

    @str($user->name)  <!-- Renders trimmed/lowercased name -->
    
  • Form Requests: Sanitize inputs in prepareForValidation:

    public function prepareForValidation()
    {
        $this->merge([
            'name' => Str::of($this->name)->trim()->value(),
        ]);
    }
    

Gotchas and Tips

Pitfalls

  1. Null Handling:

    • Str::of(null) returns an empty Str instance (safe).
    • Gotcha: Chaining methods on null won’t throw errors, but value() returns null. Explicitly check with isEmpty() if needed:
      if (Str::of($var)->isEmpty()) { ... }
      
  2. Encoding Assumptions:

    • Methods like ascii() or slug() assume UTF-8 input. For non-UTF-8 strings, normalize first:
      $normalized = mb_convert_encoding($str, 'UTF-8');
      Str::of($normalized)->slug();
      
  3. Method Chaining Order:

    • Some methods (e.g., replace()) are stateful. Order matters:
      // Wrong: Replaces after trimming (may miss leading/trailing spaces)
      Str::of('  foo  ')->replace(' ', '')->trim();
      
      // Correct: Trim first
      Str::of('  foo  ')->trim()->replace(' ', '');
      
  4. Performance:

    • Avoid over-chaining for simple operations. Example:
      // Less efficient:
      Str::of($str)->upper()->lower()->value(); // Redundant
      
      // Better:
      Str::of($str)->value(); // Just return as-is
      

Debugging Tips

  1. Inspect Intermediate States: Use ->__toString() for debugging:

    $str = Str::of('Test')
        ->upper()
        ->__toString(); // "TEST" (visible in logs/dd())
    
  2. Common Errors:

    • Call to undefined method: Ensure you’re using Str::of() (not new Str() directly).
    • Argument 1 passed to Str::of() must be string: Pass null or empty strings explicitly:
      Str::of($maybeNull ?? '');
      

Extension Points

  1. Custom Methods: Extend the class via traits or inheritance:

    use Str\Str;
    
    class CustomStr extends Str {
        public function customMethod()
        {
            return $this->prepend('custom-');
        }
    }
    
  2. Add to Laravel’s Str Facade: Override Laravel’s Str facade to use this package:

    // config/app.php
    'aliases' => [
        'Str' => Str\Str::class,
    ];
    

    Caveat: This replaces Laravel’s native Str helpers. Use cautiously.

  3. Testing: Mock Str in tests for isolated string logic:

    $this->partialMock(Str\Str::class, ['slug'])
        ->shouldReceive('slug')
        ->andReturn('mocked-slug');
    

Configuration Quirks

  • No Config File: The package is zero-config. All behavior is method-driven.
  • Locale Awareness: Methods like title() or slug() rely on PHP’s default locale. Set it globally if needed:
    setlocale(LC_ALL, 'en_US.UTF-8');
    

Pro Tips

  1. Compose with Collections: Apply Str to Laravel Collections:

    $titles = $posts->pluck('title')->map(fn($title) => Str::of($title)->title());
    
  2. Reverse Engineering: Use Str::of($str)->getValueObject() to inspect the underlying string object (for advanced use cases).

  3. Performance Benchmark: Compare against native PHP for critical paths:

    // Benchmark Str::slug() vs. custom function
    $str = 'Laravel 10';
    $time = microtime(true);
    Str::of($str)->slug();
    echo microtime(true) - $time; // ~0.0001s
    
  4. IDE Support: Enable PHPStan or Psalm for static analysis of Str method chains to catch type issues early.

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport