RobotLoader: Class Autoloading
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'; ...
composer require nette/robot-loader
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 specify what directories to index and where to save the cache:
$loader = new Nette\Loaders\RobotLoader; // directories to be indexed by RobotLoader (including subdirectories) $loader->addDirectory(__DIR__ . '/app'); $loader->addDirectory(__DIR__ . '/libs'); // use 'temp' directory for cache $loader->setCacheStorage(new Nette\Caching\Storages\FileStorage(__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->autoBuild determines whether RobotLoader should reindex the scripts if asked for
nonexistent class. This feature is disabled by default on production server.
Therefore, you need to delete the cache when you upload a new version of the application to the hosting.
If you want RobotLoader to skip some directory, create a file there called
From this point on, the Zend directory will not be indexed.
Inside Nette application, where
$configurator is used in
bootstrap.php, you can setup RobotLoader
$configurator = new Nette\Configurator; ... $configurator->setTempDirectory(__DIR__ . '/../temp'); $configurator->createRobotLoader() ->addDirectory(__DIR__) ->addDirectory(__DIR__ . '/../libs') ->register();