3.4.4 The App Class

Loading additional classes has become more streamlined in CakePHP. In previous versions there were different functions for loading a needed class based on the type of class you wanted to load. These functions have been deprecated, all class and library loading should be done through App::import() now. App::import() ensures that a class is only loaded once, that the appropriate parent class has been loaded, and resolves paths automatically in most cases.

3.4.4.1 Using App::import()

App::import($type, $name, $parent, $search, $file, $return)

At first glance App::import seems complex, however in most use cases only 2 arguments are required.

3.4.4.2 Importing Core Libs

Core libraries such as Sanitize, and Xml can be loaded by:

<?php App::import('Core', 'Sanitize') ?>
  1. <?php App::import('Core', 'Sanitize') ?>

The above would make the Sanitize class available for use.

3.4.4.3 Importing Controllers, Models, Components, Behaviors, and Helpers

All application related class should also be loaded with App::import(). The following examples illustrate how to do so.

3.4.4.3.1 Loading Controllers

App::import('Controller', 'MyController')

3.4.4.3.2 Loading Models

App::import('Model', 'MyModel')

3.4.4.3.3 Loading Components

App::import('Component', 'Auth');

3.4.4.3.4 Loading Behaviors

App::import('Behavior', 'Tree');

3.4.4.3.5 Loading Helpers

App::import('Helper', 'Html')

3.4.4.4 Loading from Plugins

Loading classes in plugins works much the same as loading app and core classes except you must specify the plugin you are loading from.

App::import('Model', 'PluginName.Comment');
  1. App::import('Model', 'PluginName.Comment');

3.4.4.5 Loading Vendor Files

The vendor() function has been deprecated. Vendor files should now be loaded through App::import() as well. The syntax and additional arguments are slightly different, as vendor file structures can differ greatly, and not all vendor files contain classes.

The following examples illustrate how to load vendor files from a number of path structures. These vendor files could be located in any of the vendor folders.

3.4.4.5.1 Vendor examples

To load vendors/geshi.php

App::import('Vendor', 'geshi');
  1. App::import('Vendor', 'geshi');

To load vendors/flickr/flickr.php

App::import('Vendor', 'flickr/flickr');
  1. App::import('Vendor', 'flickr/flickr');

To load vendors/some.name.php

App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));
  1. App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));

To load vendors/services/well.named.php

App::import('Vendor', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));
  1. App::import('Vendor', 'WellNamed', array('file' => 'services'.DS.'well.named.php'));