I’m wondering what the best practice is for handling the problem with having to ‘include’ so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script.
Currently, I’m just using include_once to include the classes I access directly. Each of those would include_once the classes that they access.
I’ve looked into using the __autoload function, but hat doesn’t seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you’d end up walking the directory tree until you found the class you were looking for. Also, I’m not sure how this effects classes with the same name in different namespaces.
Is there an easier way to handle this?
Or is PHP just not suited to ‘enterprisey‘ type applications with lots of different objects all located in separate files that can be in many different directories.
I my applications I usually have
setup.phpfile that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map.Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, __autoload function looks up class name in that array and gets include path. Here’s the code:
autobuild.php
autoload.php
Note that file naming convention must be [class_name].class.php. Alter the directories classes will be looked in
autobuild.php. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop.Serialized arrays are darn fast.
@JasonMichael: PHP 4 is dead. Get over it.