PHP Application Structure

One of the first things you do when you create a PHP application, is to create a good directory structure.

Many people have their own way of doing things and this is good. The most important thing is that people take the time to think of a good way to do stuff.

Today I'll share mine. I'm not saying this is the best way of doing stuff, this is simply a system that worked well for me.

Here's my main listing:

  • lib/
  • conf/
  • resources/
  • index.php

As you can see, I only have 3 directories, each with a specific purpose, and I'm always using a single index.php which handles all the requests.

lib/

This is where my class libraries go. All the classes are in a PEAR-structure, this means: 1 class per file, and the file/directory maps exactly to the classname, for example:the class Services_MetaWebLog can be found in lib/Services/MetaWebLog.php

There are a few good reasons why this is a good way to structure your classes:

  • Many systems already use this structure, so if you need foreign libraries (from PEAR, Solar or whatever) you usually can just copy-paste their classes in your structure
  • It allows you to easily find certain classes
  • It allows a pretty cool __autoload() function
  • If you are using subversion, you can easily include other projects libraries with the svn:externals keyword

This is the `__autoload` function, in case you need it. It's a bit simplified, but you'll get the point.

<?php
function __autoload($classname) {
  require_once 'lib/' . str_replace('_', '/', $classname) . '.php';
}

conf/

This is where global application configuration goes. In my case its usually a settings.xml with for example the database DSN.

Another tip is to put you apache configuration here. You can easily create a symlink to your /etc/apache2/sites-enabled . This way you can keep your apache configuration near to your applicaton. If you use Apache1, simply do an Include to this file.

resources/

This is where I put all the static stuff (I guess static would also have been a good name). My sub-directories tend to look like this:

  • css/
  • templates/
  • images/
  • js/
  • swf/

Good luck!