Loading Classes

Loading Classes
     Custom Autoloaders
         Example: Zend
             Download and install the Zend Framework files
             Include Zend's Autoloader in your bootstrap
             Usage example

BootPHP takes advantage of PHP autoloading. This removes the need to call include or require before using a class. When you use a class BootPHP will find and include the class file for you. For instance, when you want to use the Cookie::set method, you simply call:

Cookie::set('mycookie', 'any string value');

Or to load an Encrypt instance, just call Encrypt::instance:

$encrypt = Encrypt::instance();

Classes are loaded via the BootPHP::auto_load method, which makes a simple conversion from class name to file name:

  1. Classes are placed in the `classes/` directory of the filesystem
  2. Any underscore characters in the class name are converted to slashes
  3. The filename is lowercase

When calling a class that has not been loaded (eg: `Session_Cookie`), BootPHP will search the filesystem using BootPHP::find_file for a file named `classes/session/cookie.php`.

If your classes do not follow this convention, they cannot be autoloaded by BootPHP. You will have to manually included your files, or add your own autoload function.

Custom Autoloaders

BootPHP's default autoloader is enabled in `application/bootstrap.php` using spl_autoload_register:

spl_autoload_register(array('BootPHP', 'auto_load'));

This allows BootPHP::auto_load to attempt to find and include any class that does not yet exist when the class is first used.

Example: Zend

You can easily gain access to other libraries if they include an autoloader. For example, here is how to enable Zend's autoloader so you can use Zend libraries in your BootPHP application.

Download and install the Zend Framework files

  • Download the latest Zend Framework files.
  • Create a `vendor` directory at `application/vendor`. This keeps third party software separate from your application classes.
  • Move the decompressed Zend folder containing Zend Framework to `application/vendor/Zend`.

Include Zend's Autoloader in your bootstrap

Somewhere in `application/bootstrap.php`, copy the following code:

/**
 * Enable Zend Framework autoloading
 */
if ($path = BootPHP::find_file('vendor', 'Zend/Loader'))
{
    ini_set('include_path',
    ini_get('include_path').PATH_SEPARATOR.dirname(dirname($path)));

    require_once 'Zend/Loader/Autoloader.php';
    Zend_Loader_Autoloader::getInstance();
}

Usage example

You can now autoload any Zend Framework classes from inside your BootPHP application.

if ($validate($this->request->post()))
{
    $mailer = new Zend_Mail;

    $mailer->setBodyHtml($view)
        ->setFrom(BootPHP::$config->load('site')->email_from)
        ->addTo($email)
        ->setSubject($message)
        ->send();
}