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

Robot Loader Laravel Package

nette/robot-loader

Nette RobotLoader is a fast, zero-configuration autoloader for PHP that automatically discovers classes, caches results for performance, and rebuilds when files change. Ideal for Nette apps and standalone projects needing reliable class loading.

View on GitHub
Deep Wiki
Context7

Getting Started

RobotLoader is a high-performance autoloader for discovering and loading PHP classes, traits, and interfaces within your project—ideal for frameworks or tooling where dynamic class discovery is needed (e.g., plugins, commands, services). It caches metadata about class locations, avoiding require/include overhead on every request.

First use case: Bootstrap an autoloader in your app’s entrypoint (e.g., index.php or bootstrap.php) to auto-discover classes in your src/ directory:

use Nette\RobotLoader;

$loader = new RobotLoader();
$loader->addDirectory(__DIR__ . '/src');
$loader->setTempDirectory(__DIR__ . '/temp/cache/robotloader'); // 🛑 must be set explicitly
$loader->register(); // registers __autoload hook

💡 Where to look first:

  • README explains core methods: addDirectory(), excludeDirectory(), refresh(), getClasses().
  • Start with getClasses() to inspect what’s been discovered (especially during debugging).
  • Use refresh() manually to rebuild the cache (e.g., in deploy hooks or dev tools).

Implementation Patterns

1. Production Autoloading with Caching

RobotLoader’s main value is speed via caching. In production:

  • Call $loader->refresh() once (e.g., during deploy) to generate the cache.
  • Then let it auto-rebuild on-demand (enabled by default since v3.3.0): register() + first class load triggers cache regeneration if stale.
// deploy script
$loader = new RobotLoader();
$loader->addDirectory(__DIR__ . '/src');
$loader->setTempDirectory(__DIR__ . '/var/cache/robotloader');
$loader->excludeDirectory('src/Tests');
$loader->refresh(); // eager cache build

2. Dynamic Discovery + Lazy Loading

Use RobotLoader to scan for service implementations, commands, or plugins without pre-registering them:

$loader = new RobotLoader();
$loader->addDirectory(__DIR__ . '/plugins');
$loader->setTempDirectory(__DIR__ . '/cache');
$loader->register();

// Later, resolve a class dynamically:
$className = 'Plugin\\Auth\\LoginCommand';
$reflection = new ReflectionClass($className); // triggers class loading if not already loaded

3. Custom Class Discovery Filters

Fine-tune what gets indexed using setAcceptFiles() and setExcludeDirectories():

$loader = new RobotLoader();
$loader->addDirectory(__DIR__ . '/modules');
$loader->setAcceptFiles(['*.php']); // default
$loader->excludeDirectory('Modules/Dev');
$loader->excludeDirectory('Modules/Test'); // supports trailing slashes

4. Static Analysis Tooling

Leverage getClasses() to generate config (e.g., for DI containers or command registries):

$loader = new RobotLoader();
$loader->addDirectory(__DIR__ . '/src');
$loader->setTempDirectory(__DIR__ . '/cache');
$loader->refresh();

file_put_contents('services.json', json_encode([
    'commands' => array_filter($loader->getClasses(), fn($c) => is_subclass_of($c, Command::class)),
]));

Gotchas and Tips

🔥 Critical Pitfalls

  • No composer.json integration: RobotLoader does not integrate with Composer’s autoloading. You must use it instead of Composer (e.g., drop classmap from Composer), or risk duplicate loads. Use only one autoloader strategy.
  • setTempDirectory() is mandatory since v2.4.2. Omitting it throws an exception in v2.4.4+.
  • Absolute paths only for temp directory (v4.0.2+). Relative paths fail silently or throw.
  • Case sensitivity: Since v3.0.0, class lookups are case-sensitive (e.g., Useruser). This avoids filesystem edge cases (e.g., macOS vs. Linux), but requires strict naming.

⚙️ Debugging & Tuning

  • Cache invalidation: Use refresh() when adding/removing files. By default, RobotLoader rebuilds the cache lazily on class access (v3.3.0+), but refresh() ensures upfront generation.
  • Check cache health: Inspect $loader->getCacheKey() and verify the temp directory contains .cache files.
  • Parse errors: Enable reportParseErrors(true) (default) to fail fast on syntax errors. Disable with reportParseErrors(false) if scanning untrusted code.

🧩 Extension Points & Best Practices

  • Use acquireLock() in concurrent environments (v3.2.3+) to prevent race conditions during cache rebuild.
  • Avoid large directories: Nest directories (e.g., addDirectory('src/Commands'), addDirectory('src/Events')) instead of one root src/ with thousands of files.
  • Custom cache storage?: Not supported since v3.0.0—RobotLoader uses its own simple file-based cache. The API is opinionated for reliability.
  • PHP version constraints: Ensure your php version matches the library version (v4.x requires PHP 8.1+). Use composer platform check to verify ext-tokenizer is present.

💡 Pro tip: Wrap RobotLoader in a factory to centralize config:

function createRobotLoader(): RobotLoader {
    $loader = new RobotLoader();
    $loader->addDirectory(__DIR__ . '/src');
    $loader->excludeDirectory('src/Tests');
    $loader->setTempDirectory(__DIR__ . '/cache/robotloader');
    $loader->setAcceptFiles(['*.php']);
    return $loader;
}
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