THE LAB/
PHP Example – Factory Class
In the last example, we looked at how classes are created in PHP, after a brief overview of the entire language. I also did some kvetching about some of the loose ends of the language. To be fair, let’s look at a simple little example of something that PHP is great for – a factory class.
The purpose of a factory class is to centralize the creation of assets for your application. It keeps you from having to change code in a thousand places (and introducing extra bugs) if the requirements of your application change.
In a compiled language, factories are limited by the fact that classes need to be compiled into the finished bytecode to be used. In AS3, for instance, if you do not have a reference somewhere in your code to a class, that class will not be compiled into the finished swf. The purpose of this is to keep filesize small. (Note that if you use the compc compiler you can actually request it to include classes not explicitly referenced in your code).
Since PHP is an interpreted language that gets interpreted server-side, this limitation does not apply. With PHP, any time you need a piece of code, you can just include it and you are up and running with it. This makes the creation of a factory class a very powerful and simple device in this language.
Let’s look at an example;
<?php class ClassFactory { const CLASSLOCATION = "."; //being able to do something like this is pure joy, //and probably the biggest strength of a dynamic interprested //language like PHP. You could never do this in a compiled language //like AS3. public function create($type) { if(include_once ClassFactory::CLASSLOCATION."/".$type . '.php'){ return new $type; }else{ echo ("Class $type not found in ".ClassFactory::CLASSLOCATION); } } } ?>
This again illustrates a few key concepts of PHP.
1. Notice the use of the variable constant. Constants are set one time and can not be changed. PHP has a foible where constant variables are NOT prefaced with a dollar sign, unlike other variable types in the language.
2. You use a dot for concatenation of strings (line 11).
3. The double-colon (I refuse to call it by the crazy name they give it) is used to define the scope of the variable reference, but note that it will only work with static methods and members, and constant variables.
4. You can put variables into quotes and they will work just fine (line 14)
Next up, we will make a simple gateway class, that uses our factory to access a whole code library, and we’ll look at PHP’s powerful reflection abilities.