🍀 Nette RobotLoader: high performance and comfortable autoloader that will search and autoload classes within your application.
RobotLoader is a tool that gives you comfort of automated class loading for your entire application including third-party libraries.
- get rid of all
- only necessary scripts are loaded
- requires no strict file naming conventions
- allows more classes in single file
RobotLoader is extremely comfortable and addictive!
So we can forget about those famous code blocks:
require_once 'Utils/Page.php'; require_once 'Utils/Style.php'; require_once 'Utils/Paginator.php'; ...
Like the Google robot crawls and indexes websites, RobotLoader crawls all PHP scripts and records what classes and interfaces were found in them. These records are then saved in cache and used during all subsequent requests. You just need to specifiy what directories to index and where to save the cache.
Install it using Composer:
composer require nette/robot-loader
It requires PHP version 5.6 or newer (is compatible with PHP 7.0 and 7.1).
$loader = new Nette\Loaders\RobotLoader; // Add directories for RobotLoader to index $loader->addDirectory(__DIR__ . '/app'); $loader->addDirectory(__DIR__ . '/libs'); // And set caching to the 'temp' directory $loader->setTempDirectory(__DIR__ . '/temp'); $loader->register(); // Run the RobotLoader
And that's all. From now on, you don't need to use
require. Great, isn't it?
When RobotLoader encounters duplicate class name during indexing, it throws an exception and informs you about it.
$loader->setAutoRefresh(true or false) determines whether RobotLoader should reindex files if asked for nonexistent class.
This feature should be disabled on production server.
If you want RobotLoader to skip some directory, use