Registering classes

In PHPDevShell classes can be registered into the framework, either manually (in a config file) or from the database (usually by a plugin installation).

A registered class can be instanciated with the built-in factory, allowing some nice features:
- auto instanciation
- singleton
- auto dependency injection
- class aliasing (i.e. class override)

Class aliasing means that you can provide a class which will be used instead of another class and still be a daughter of of this class ; for example let's say I want to override the default login mecanism:

in the class file (/plugins/MY-plugins/includes/MY-login.class.php):

	class MY_login extends StandardLogin

and in my config file (/plugins/MY-plugins/config/mysite.config.php):

	$this->classes->registerClass('MY_login', 'StandardLogin', 'MY-plugin');

you can also define a class registration in the database with GUI (System Management -> System Admin -> Class Registry).

When the framework need the StandardLogin instance, it will do something like:

	$l = $this->factory('StandardLogin');

and $l will contain an instance of your class MY-login. It's magic!

A few notes:
- only the registration is recorded, allowing the config file (which are executed very early) to override the database
- if a class name is prefixed with the ampersand symbol ('&') it's a singleton
- if a class name is prefixed with the sharp sympa ('#') it's auto-instanciated

PS: I wrote this post because of a little change in the 3.5 release ; previously a class in the database would replace a class defined in the config file

PHPDevShell © 2010 - All rights reserved.