Weave 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

Jetpack Autoloader Laravel Package

automattic/jetpack-autoloader

Composer autoloader drop-in for WordPress and PHP projects that avoids class conflicts across bundled plugins/themes. Provides a custom autoloader to isolate vendor libraries, improve compatibility, and reduce “cannot redeclare class” errors in complex installs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add to your plugin/theme's composer.json:

    {
        "require": {
            "automattic/jetpack-autoloader": "^2"
        }
    }
    

    Run composer install or composer update.

  2. Load the Autoloader In your plugin's main file (e.g., my-plugin.php), include the generated autoloader:

    require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload_packages.php';
    
  3. Verify Compatibility Ensure all plugins/themes using shared dependencies also adopt this autoloader to guarantee version consistency.

First Use Case: Resolving Dependency Conflicts

If your plugin relies on a package (e.g., vendor/package) and another plugin uses an older version, this autoloader ensures the latest version is loaded. Example:

// Instead of relying on Composer's default autoloader,
// this will always load the newest version of `Vendor\Package\Class`.
new Vendor\Package\Class();

Implementation Patterns

Core Workflow

  1. Autoload Generation

    • Run composer dump-autoload -o to generate optimized classmaps (jetpack_autoload_classmap.php).
    • The autoloader prioritizes semantic versions but respects JETPACK_AUTOLOAD_DEV for dev packages (e.g., 9999999-dev).
  2. Plugin Integration

    • Main Plugin File: Load autoload_packages.php early (before plugins_loaded if possible).
    • Hooks: Use plugins_loaded to defer non-critical autoloads and avoid conflicts:
      add_action('plugins_loaded', function() {
          // Safe to load classes here.
          new Vendor\Package\Class();
      });
      
  3. Development vs. Production

    • Dev Mode: Set define('JETPACK_AUTOLOAD_DEV', true); to prefer dev-* versions.
    • Production: Defaults to semantic versioning (e.g., 2.0.0 > 1.0.0).

Advanced Patterns

  • PSR-4 to Classmap Conversion The autoloader converts PSR-4 autoloads to classmaps during composer dump-autoload -o, improving performance.

  • Transient Caching Uses WordPress transients to cache plugin lists, reducing lookup overhead. Clear transients with:

    delete_transient('jetpack_autoloader_plugins');
    
  • Debugging Early Loads Enable debug mode to catch classes loaded before plugins_loaded:

    define('JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS', true);
    

Integration Tips

  • Avoid Conflicts: Ensure all plugins/themes using shared packages adopt this autoloader.
  • Optimize: Use --optimize with Composer commands for faster loads in production.
  • Namespace Standards: Follow WordPress Coding Standards for classmap compatibility.

Gotchas and Tips

Pitfalls

  1. Classmap Staleness

    • Issue: Moving/renaming classes post-update breaks autoloading because the classmap isn’t regenerated dynamically.
    • Fix: Regenerate classmaps after updates:
      composer dump-autoload -o
      
    • Workaround: Pre-load classes during plugin updates (handled automatically for non-PSR-4 classes).
  2. Version Hierarchy Conflicts

    • Issue: A newer class in a lower-versioned package (e.g., 0.1.0) may be ignored if an older package (e.g., 2.0.1) exists.
    • Fix: Ensure package versions align with class versioning logic.
  3. Transient Cache Masking

    • Issue: Transients may hide autoloader issues (e.g., missing plugins).
    • Debug: Clear transients or use:
      define('JETPACK_AUTOLOAD_DEBUG_CONFLICTING_LOADERS', true);
      
  4. Early Loading Errors

    • Issue: Classes loaded before plugins_loaded may conflict with later plugins.
    • Debug: Enable JETPACK_AUTOLOAD_DEBUG_EARLY_LOADS and defer loads:
      add_action('plugins_loaded', function() { /* Load here */ });
      
  5. Composer Autoloader Conflicts

    • Issue: Other autoloaders (e.g., from autoload.php) may override this one.
    • Fix: Ensure this autoloader runs first by checking spl_autoload_register() priorities.

Debugging Tips

  • Check Autoloader Paths:
    var_dump(file_exists(plugin_dir_path(__FILE__) . 'vendor/autoload_packages.php'));
    
  • Validate Classmaps: Inspect vendor/composer/jetpack_autoload_classmap.php for missing/incorrect entries.
  • Log Conflicts: Enable debug constants to log conflicts to error_log:
    define('JETPACK_AUTOLOAD_DEBUG', true);
    

Extension Points

  • Custom Classmap Generation: Extend AutoloadGenerator to modify classmap logic (e.g., exclude files).
  • Dev Environment Overrides: Use JETPACK_AUTOLOAD_DEV to force dev versions during testing.
  • Plugin-Specific Autoloads: Register additional classmaps via jetpack_autoloader_classmap filter:
    add_filter('jetpack_autoloader_classmap', function($classmap) {
        $classmap['Vendor\\CustomClass'] = __DIR__ . '/custom-path.php';
        return $classmap;
    });
    

Configuration Quirks

  • Vendor Directory: Must use the default vendor/ directory (not custom paths).
  • Composer 2.x: Requires Composer ≥2.2 (drop-in support for PSR-4/classmap).
  • PHP 8+: Uses strict types; ensure compatibility with declare(strict_types=1).

Performance Notes

  • Optimized Mode: Use -o flag for ~30% faster loads (classmaps instead of PSR-4).
  • Transient TTL: Defaults to 24 hours; adjust with:
    add_filter('jetpack_autoloader_transient_lifetime', function() {
        return HOUR_IN_SECONDS; // Shorter cache for testing.
    });
    
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.
quimgc/tasks
sistem-atc/bank-sdk
core45/laravel-cookieconsent
projectsend/community-modules
ovac/laravel-hubtel-payment
capimail/capimail-php
shiroamada/green-api-laravel-notification
shiroamada/ultrasms-laravel-notification
esazykin/laravel-clickhouse
nbrabant/laraadmin
tobya/saloonfire
kjmtrue/laravel-debugbar
hexincorp/debugbar
razorbacks/laravel-shibboleth
adilazhari/laravel-idempotency
mamitech/laravel-slow-query-log
mamitech/laravel-http-logger
medeirosrafael/docxmustache
webdevlabs/phreak
vis/log-envelope