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

Stdlib Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require hyperf/stdlib
    

    Ensure your composer.json specifies a compatible version (e.g., "hyperf/stdlib": "^3.1").

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

    • Helpers: Browse Hyperf\Stdlib namespace for Arr, Str, Collection, Json, etc.
    • Documentation: Check the Hyperf Stdlib docs (or generated PHPDoc) for method signatures.
    • Autoloading: No manual configuration needed—helpers are PSR-4 autoloaded.
  4. Quick Wins:

    • Replace array_merge_recursive with Arr::deepMerge().
    • Use Collection::make() for fluent array operations (e.g., filtering, mapping).
    • Leverage Str::camel() or Str::snake() for naming conventions.

Implementation Patterns

Usage Patterns

  1. 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();
    
  2. Validation Logic: Use Arr for nested input sanitization:

    use Hyperf\Stdlib\Arr;
    
    $cleanInput = Arr::only($request->all(), ['user', 'metadata']);
    
  3. Shared Utility Layer:

    • Logging: Extend Json::prettyPrint() for debug logs.
    • Caching: Use Arr::dot() to flatten config keys for Redis.
    • Error Handling: Standardize error messages with Str::headline().
  4. Hyperf-Specific Integrations:

    • Coroutines: Use Collection::async() for batch processing:
      $results = Collection::make($tasks)
          ->async(fn($task) => $this->processTask($task))
          ->all();
      
    • DI Container: Bind custom utilities to hyperf/stdlib helpers:
      $container->bind('app.helpers', fn() => new class {
          public function __call($method, $args) {
              return Arr::$method(...$args);
          }
      });
      
  5. Configuration Management: Merge configs across services with Arr::deepMerge():

    $mergedConfig = Arr::deepMerge(
        require __DIR__.'/config/base.php',
        require __DIR__.'/config/override.php'
    );
    

Workflows

  1. Migrating Custom Helpers:

    • Step 1: Replace array_column() with Collection::pluck().
    • Step 2: Use Arr::get() instead of isset($array[$key]).
    • Step 3: Adopt Str::* for string manipulations (e.g., Str::limit()).
  2. Testing Utilities:

    • Mock hyperf/stdlib helpers in PHPUnit:
      $this->partialMock(Arr::class, ['get'])->shouldReceive('get')->andReturn($mockData);
      
  3. Performance Optimization:

    • Benchmark Collection vs. native PHP for large datasets:
      $collection = Collection::make(range(1, 100000));
      $collection->sum(); // Compare with array_sum()
      

Integration Tips

  • Leverage Hyperf’s DI: Bind hyperf/stdlib helpers as singletons in config/autoload.php:
    'dependencies' => [
        Arr::class => Hyperf\Stdlib\Arr::class,
    ],
    
  • Extend Functionality: Create a 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']);
        }
    }
    
  • Avoid Overuse: Prefer native PHP for micro-optimizations (e.g., foreach over Collection::each() for tiny arrays).

Gotchas and Tips

Pitfalls

  1. Hyperf-Specific Assumptions:

    • Some methods (e.g., Coroutine-aware helpers) may fail in non-Hyperf contexts.
    • Example: Collection::async() requires Hyperf’s go functions.
  2. Namespace Collisions:

    • Avoid naming custom classes Arr, Str, etc., to prevent autoloading conflicts.
  3. 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]
      
  4. 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]);
      
  5. Deprecated Methods:

    • Check changelogs for removed methods (e.g., Arr::setValue()Arr::set()).

Debugging Tips

  1. Enable Strict Typing: Use declare(strict_types=1) to catch type mismatches in helper methods.

  2. 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);
        });
    }
    
  3. Check for Coroutine Leaks: Ensure async helpers (e.g., Collection::async()) are awaited:

    $results = yield Collection::make($tasks)->async(fn($task) => $task());
    

Configuration Quirks

  1. Autoloading: Ensure composer dump-autoload is run after installation.

  2. Custom Helpers: Extend hyperf/stdlib by publishing macros:

    Arr::macro('customMerge', function ($array1, $array2) {
        return Arr::deepMerge($array1, $array2);
    });
    
  3. Environment-Specific Behavior: Override helpers in config/autoload.php:

    'stdlib' => [
        'default_locale' => env('APP_LOCALE', 'en_US'),
    ],
    

Extension Points

  1. Create Custom Collections: Extend Hyperf\Stdlib\Collection:

    class UserCollection extends Collection {
        public function activeOnly(): self {
            return $this->filter(fn($user) => $user['active']);
        }
    }
    
  2. Add Global Helpers: Register macros in a service provider:

    public function boot(): void {
        Arr::macro('path', function ($array, $path) {
            return Arr::get($array, $path);
        });
    }
    
  3. Integrate with Hyperf Components:

    • Validation: Use Arr in hyperf/validation rules:
      $validator->rule('required', Arr::get($data, 'user.name'));
      
    • Middleware: Sanitize input with Arr::only():
      public function handle($request, Closure $next) {
          $cleanData = Arr::only($request->all(), ['id', 'name']);
          $request->merge($cleanData);
          return $next($request);
      }
      

Pro Tips

  • Use Collection::when() for Conditional Logic:
    $collection = Collection::make($items)
        ->when($flag, fn($c) => $c->filter(fn($item) => $item['active']))
        ->pluck('id');
    
  • Leverage Arr::dot() for Config: Flatten nested configs for Redis or env vars:
    $flatConfig = Arr::dot(['db' => ['host' => 'localhost']]);
    // Returns 'db.host=localhost'
    
  • Combine with Hyperf’s make: Generate utility classes dynamically:
    $helper = app()->makeWith(Hyperf\Stdlib\Arr::class, ['config']);
    
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