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

Polyfill Laravel Package

symfony/polyfill

Symfony Polyfill backports newer PHP features and provides compatibility layers for missing extensions and functions. Use it to keep apps portable across PHP versions, smoothing gaps in intl, mbstring/iconv, uuid, and many core APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Identify Required Polyfills: Check your php -r "echo PHP_VERSION;" and missing extensions (e.g., mbstring, intl). Use the README to map features to standalone packages (e.g., symfony/polyfill-mbstring for mbstring functions).

  2. Install via Composer:

    composer require symfony/polyfill-mbstring symfony/polyfill-php80
    

    Replace with the specific polyfills needed (e.g., symfony/polyfill-intl-idn for idn_to_ascii).

  3. First Use Case: Use PHP 8.0+ functions like str_contains() in PHP 7.4:

    use Symfony\Polyfill\String\Stringable;
    
    $stringable = new Stringable('hello');
    $contains = $stringable->contains('ell'); // true
    

Implementation Patterns

1. Version-Agnostic Code

  • Pattern: Use polyfills to write code compatible across PHP versions.
  • Example: Leverage array_key_first() in PHP 7.3+:
    use Symfony\Polyfill\Php73\array_key_first;
    
    $keys = array_key_first(['a' => 1, 'b' => 2]); // 'a'
    

2. Extension Polyfills

  • Pattern: Replace missing extensions (e.g., mbstring) with polyfills.
  • Example: Use mb_strlen() without the mbstring extension:
    use Symfony\Polyfill\Mbstring\Mbstring;
    
    $length = Mbstring\mb_strlen('こんにちは'); // 5
    

3. Lazy-Loading Overhead

  • Pattern: Polyfills load only when used (e.g., Stringable for str_contains).
  • Optimization: Exclude unused polyfills via composer.json:
    "replace": {
        "symfony/polyfill-php73": "*" // Skip if PHP ≥ 7.3
    }
    

4. Integration with Laravel

  • Pattern: Use polyfills in service providers or helpers.
  • Example: Add Stringable to a helper:
    use Symfony\Polyfill\String\Stringable;
    
    if (!function_exists('str_starts_with')) {
        Stringable::register();
    }
    

5. Testing Compatibility

  • Pattern: Test polyfills alongside native implementations.
  • Example: Mock str_contains in tests:
    use Symfony\Polyfill\String\Stringable;
    
    $stringable = new Stringable('test');
    $this->assertTrue($stringable->contains('es')); // true
    

Gotchas and Tips

Pitfalls

  1. Direct symfony/polyfill Requirement:

    • ❌ Avoid requiring symfony/polyfill directly—it bloats dependencies.
    • ✅ Use standalone packages (e.g., symfony/polyfill-php80).
  2. Extension Conflicts:

    • Polyfills may conflict with native extensions (e.g., mbstring polyfill vs. installed mbstring).
    • Fix: Use replace in composer.json to exclude polyfills when extensions are available.
  3. Closure Deep Cloning:

    • deepclone polyfill may fail with closures or complex objects.
    • Tip: Use DEEPCLONE_HYDRATE_PRESERVE_REFS flag for circular references:
      use Symfony\Polyfill\DeepClone\deepclone;
      
      $cloned = deepclone($obj, DEEPCLONE_HYDRATE_PRESERVE_REFS);
      
  4. UTF-8 Handling:

    • Some polyfills (e.g., mbstring) may misbehave with invalid UTF-8.
    • Tip: Validate input with mb_check_encoding() or iconv.
  5. Performance Overhead:

    • Polyfills add minimal runtime cost but may impact boot time.
    • Tip: Exclude unused polyfills via replace or autoload-dev.

Debugging Tips

  1. Check Polyfill Registration:

    • Verify functions/classes are loaded:
      if (!function_exists('str_contains')) {
          throw new \RuntimeException('Polyfill not loaded!');
      }
      
  2. Extension Detection:

    • Debug missing extensions:
      if (!extension_loaded('mbstring')) {
          echo 'Install mbstring or use polyfill.';
      }
      
  3. Deep Clone Issues:

    • Debug serialization errors with:
      try {
          $cloned = deepclone($obj);
      } catch (\Exception $e) {
          var_dump($e->getMessage());
      }
      

Extension Points

  1. Custom Polyfills:

    • Extend existing polyfills by subclassing (e.g., Stringable).
    • Example: Add a custom str_contains wrapper:
      class CustomStringable extends Stringable {
          public function containsIgnoreCase(string $needle): bool {
              return str_contains(strtolower($this->string), strtolower($needle));
          }
      }
      
  2. Bootstrap Optimization:

    • Override vendor/autoload.php to load only needed polyfills:
      require __DIR__.'/symfony/polyfill-php80/Resources/stubs/stringable.php';
      
  3. PHP 8 Attributes:

    • Use polyfilled attributes (e.g., #[Attribute]) in PHP < 8.0:
      use Symfony\Polyfill\Php80\Attribute\Attribute;
      
      #[Attribute]
      class CustomAttribute {}
      

Laravel-Specific Quirks

  1. Service Provider Registration:

    • Register polyfills in AppServiceProvider:
      public function boot() {
          if (!function_exists('str_contains')) {
              Stringable::register();
          }
      }
      
  2. Blade Directives:

    • Use polyfills in Blade templates:
      @php
          use Symfony\Polyfill\String\Stringable;
          $stringable = new Stringable('hello');
      @endphp
      
  3. Artisan Commands:

    • Ensure polyfills are loaded in commands:
      use Symfony\Polyfill\Php80\Stringable;
      
      class MyCommand extends Command {
          protected function handle() {
              Stringable::register();
              // Use str_contains() here
          }
      }
      
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle