Class Auto-loading
When working with Nette Framework, forget about including every single file
using require or include. Nette cares about your
comfort and does it itself.
- get rid of all
require - only necessary scripts are loaded
- requires no strict file naming conventions
- allows more classes in single file
We can load Nette Framework with a single command: require
'Nette/loader.php' (the path may be different of course) and all of its
classes will be loaded automatically when you use them for the first time. That
not only saves you a lot of writing, but it also accelerates entire application.
Why? Simply because only those files that are actually needed are loaded. No
unnecessary files get parsed by PHP.
Nette\Loaders\RobotLoader
Nette\Loaders\RobotLoader is a tool that gives you comfort of automated class loading for your entire application including third-party libraries. So we can forget about those famous code blocks:
require_once 'Zend/Pdf/Page.php';
require_once 'Zend/Pdf/Style.php';
require_once 'Zend/Pdf/Color/GrayScale.php';
require_once 'Zend/Pdf/Color/Cmyk.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:
$loader = new Nette\Loaders\RobotLoader;
// Add directories for RobotLoader to index
$loader->addDirectory('app');
$loader->addDirectory('libs');
// And set caching to the 'temp' directory on the disc
$loader->setCacheStorage(new Nette\Caching\Storages\FileStorage('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.
Inside sandbox, where the paths to application and library files are defined
in APP_DIR and LIBS_DIR constants and the path to
temporary directory in TEMP_DIR, it's possible to simplify the
code added to bootstrap.php:
Nette\Environment::getRobotLoader()->register();
The variable $loader->autoBuild determines whether
RobotLoader should reindex the scripts if asked for nonexistent class. This
feature is disabled by default on production server.
Therefore, it's necessary to delete the cache when uploading a new version of your application.
If you want RobotLoader to skip some directory, create a file there called
netterobots.txt:
Disallow: /Zend
From this point on, the Zend directory will not be indexed.
RobotLoader is extremely comfortable and addictive!

