HTML and CSS Reference
In-Depth Information
Autoloading Classes
Finally, to avoid loading a large number of unused PHP classes, you'll need an autoloader to grab the required files
only when they're being accessed.
This is accomplished by creating a function to search in all the places where classes will be stored; then
registering that function as the autoloader using spl_autoload_register() .
the __autoload() function used to be the standard, but php now recommends using spl_autoload_register()
due to better flexibility and performance.
Note
To start, let's refer to the app's folder structure and determine all the possible locations that may hold class files as
the app is built out.
There will be three class types loaded by this function:
system/controllers/
Controllers will be stored in
system/models/
Models are stored in
system/core/ (we'll talk more about these files later)
Core files will be stored in
Armed with the list of possible locations, the function will loop through each one and see whether the class exists
there; if so, it will load the class and return TRUE ; if not, it throws an Exception stating the class doesn't exist.
Add the following bold code to make this happen. Don't forget the call to spl_autoload_register() in the app
initialization block!
<?php
/**
* The initialization script for the app
*
* @author Jason Lengstorf <jason@lengstorf.com>
* @author Phil Leggetter <phil@leggetter.co.uk>
*/
//-----------------------------------------------------------------------------
// Initializes environment variables
//-----------------------------------------------------------------------------
// Server path to this app (i.e. /var/www/vhosts/realtime/httpdocs/realtime)
define('APP_PATH', dirname(__FILE__));
// App folder, relative from web root (i.e. /realtime)
define('APP_FOLDER', dirname($_SERVER['SCRIPT_NAME']));
// URI path to the app (i.e. http://example.org/realtime )
define(
'APP_URI',
remove_unwanted_slashes('http://' . $_SERVER['SERVER_NAME'] . APP_FOLDER)
);
 
 
Search WWH ::




Custom Search