Blog
PHP 5 features: Class autoloading
2007-12-05 11:46:11 by Martynas Jusevičius
Continuing the series about useful features in PHP 5, another overlooked one is class autoloading. From the manual:
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Basically, you get a class name as a parameter in your __autoload() function, and using it you have to figure out the path to the actual class file and include it.
If all of the classes are at known paths in known folders, you might be able to find the class file path using simple string concatenation. However, if the folder structure is more complex, a convenient solution is to have a class name/class file path map (associative array), whether hand-made or generated:
function __autoload($classname)
{
$classes = array(
"NotFoundView" => APP_VIEW_DIR."notFound/NotFoundView.class.php",
"ErrorView" => APP_VIEW_DIR."error/ErrorView.class.php"
// and so on
);
if (array_key_exists($classname, $classes)) require($classes[$classname]);
// using name as key, get the path and include the file
}There can be several autoloading functions named differently, but then they have to be registered explicitly using spl_autoload_register(). Class methods can also be used.
These hacks are not very clean, but they help to bring PHP one little step closer to object- and library-oriented approach. For example, a library (such as Propel or DIY Framework) can be implemented with its own class autoloading, and including a single file that handles it will be enough to load the whole library.
Propel 1.3 uses this feature already, and we are implementing it in the new release of the DIY Framework. The framework loader class implements autoload() method, and at the end of the file it is registered using spl_autoload_register(array("DIYFrameworkLoader", "autoload")). Including the loader class effectively loads the whole framework.
Comments (12)
A little bit of optimization… (autoload is used often, so it matters)
1) $classes can be made static
2) isset() would work a bit faster than array_key_exists
Note
NOTE: php5 supports class names being loaded in any case, be warned, if your developer does $blah = new errorview() it is valid however your autoloader will barf, as you said, propel handles it however at the moment it enforces case sensitivity as well...
Alexey,
2007-12-05 21:56:05 by Martynas
Agree about 1), the example could be better.
Speaking about 2), I never cared enough to check the performance differences of internal PHP functions :)
isset vs. array_key_exists
isset() is only faster because it isn't actually a function. It's a language operator (like empty), which generates special opcodes in place of "call function". This is because isset and empty have to access their argument carefully to prevent triggering a "Variable %s is undefined" message if the variable doesn't actually exist.
A side effect of this special access is that you can't do empty($obj->method()).
Another difference is that array_key_exists will return TRUE if the key is present, but with a NULL value. isset() will consider the NULL "not set".
But getting back to performance, my personal opinion is that if you need to loop a million times to get a measurable difference, there's not much point in applying that micro-optimization. Do what makes sense first.
Scan dir
You can alwasy create array with classes using dir scanning:
new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sPath))
with function token_get_all()
of course you have to create cache.
cartier jewelry
asfdadas
I will also provide information about your fellow students, many of whom may have similar interests. If you could complete this short questionnaire (a 1-minute process) we will begin to accumulate data for this list.
Thank you.This
I found this post while surfing the web for freebies.There seemed to me something cheap ed hardy alarming in such easy delights. In my ed hardy sale heart was desire to live more ed hardy clothing dangerously. I was not unprepared for jagged herve leger dress rocks and treacherous, shoals it I could only have change-change and the http://www.edhardy-buy.com/ exicitement of unforeseen.Thanks for sharing this article.
Great article
Thank you for your insight,the article was worth every minute reading it.However mean your authentic jordan shoes life is,meet it and live it,do not shun it and call it cheap jordans shoes hard names.It is not so bad as you cheap nike shox are.It looks poorest when you are cheap nike shoes richest.The fault-finder will find faults in http://www.nikejordanshoes2sell.com/ paradise.
Air Jordan shoes
Welcome to buy and enjoy the greatest benefits.Only those who have the nike shoes patience to do simple things perfectly ever acquire the air jordan shoes skill to do difficult things easily.If you wish to succeed,you should use prada shoes persistence as your good friend,experience as your gucci Shoes reference,prudence as your brother and hope as your http://www.nikeaf1jordanshoes.com/ sentry.Very good collection.A new showcase for this site.
burberry handbags
thank you!
gucci handbags
hello!

2007-12-05 14:55:47 by Alexey Zakhlestin