Autoloading your Classes using Namespaces
PHP 5.3+ users only!
Written by AwesomezGuy, 30th January 2011
Introduction
Sup guys? I decided I'd write a nice tutorial into autoloading your classes into your project, and also to structure your files in a nice user friendly way (I got the approach I'll be using in this tutorial from Kyek, so thank you to him
Step 1, Your File Structure
In order to do this we're going to need to get your classes nice and organized, let's go through a few rules we'll be following
- 1 Class per File - NO dissident says it is unprofessional to swear in a tutorial, so I removed this naughty word EXCEPTIONS
- Classes should be organized into groups, we don't want to lob them in all together
Let's get going with the structure!
Start by creating a folder called "lib" in your project's base directory. lib stands for library, so in future if you ever plan to use REcaptcha or something, you'll have a great place to drop that, and if you're using hydrogen it'll definitely need to go in here.
Now, the next thing you need to get into your head, we're going to think of your project's classes as a library. For this example, I'll just pretend the project in question is called myproject.
So inside that lib folder, you'll want to create a myproject folder.
So now we have /lib/myproject.
Next up! We need to start grouping your classes together! Let's say you have a few classes centred around your user system.
Let's think of them as classes called User, UserPermissionSet and UserGroup.
So we now create a folder called user inside myproject.
We now have /lib/myproject/user.
Now inside user we're going to create 3 files, User.php, UserPermissionSet.php and UserGroup.php, inside those files, we put classes named the same as the filename (minus the .php).
Woot! We now have the following:
- /lib/myproject/user/User.php
- /lib/myproject/user/UserPermissionSet.php
- /lib/myproject/user/UserGroup.php
Group all your classes like that and repeat the process, in the end you'll have a bunch of folders with class files inside them.
Step 2, Add namespaces to the files
So we have our lovely structure. Now you might be wondering why we structured everything like that. Sure, it's nice to be neat and tidy, but was that really necessary?
Yes, it was, is my answer.
When we get to the autoloading, the files are going to need to be in a structure which in someway resembles the namespaces.
Let's take our UserGroup class for example.
It's in /lib/myproject/user/UserGroup.php
The full namespace that will be used is going to be myproject\user\UserGroup, understand now?
So now we have to add the namespace line to the top of all your class files.
At the top of /lib/myproject/user/UserGroup.php, we'd put
namespace myproject\user;The last part is filled in with the class name, so we don't need to put that there.
Repeat that process for every class file you have, substituting user for the group of classes you're operating in.
Step 3, Add the autoloader
Now for the autoloader, here's an autoloader we'd use for myproject. We put it in /lib/myproject/myproject.inc.php:
<?php
namespace myproject;
function load($namespace) {
$splitpath = explode('\\', $namespace);
$path = '';
$name = '';
$firstword = true;
for ($i = 0; $i < count($splitpath); $i++) {
if ($splitpath[$i] && !$firstword) {
if ($i == count($splitpath) - 1)
$name = $splitpath[$i];
else
$path .= DIRECTORY_SEPARATOR . $splitpath[$i];
}
if ($splitpath[$i] && $firstword) {
if ($splitpath[$i] != __NAMESPACE__)
break;
$firstword = false;
}
}
if (!$firstword) {
$fullpath = __DIR__ . $path . DIRECTORY_SEPARATOR . $name . '.php';
return include_once($fullpath);
}
return false;
}
function loadPath($absPath) {
return include_once($absPath);
}
spl_autoload_register(__NAMESPACE__ . '\load');
?>Substitute the namespace for the name of your project and save the file.
Step 4, Include the autoloader into your project and use the classes
Final step. You need to add the following line to any file which uses your classes, if you're using an MVC pattern, this will only be one file.
require_once("lib/myproject/myproject.inc.php");Obviously, substitute instances of myproject with your project's name.
Now, just use the following line to use your classes (pun intended)
use myproject\user\UserGroup;
By now I seriously hope you know what you need to substitute in that line, if you don't, go read this entire thing again- slowly.
Hope you enjoyed that tutorial, if you have any questions feel free to ask below!






Cartoon Clouds
Mountains
Sunrise
Clouds
Green Clouds
None




















Help