Wednesday, April 1, 2009

Perfect PHP Setup

PHP is the first 'serious' language I've learned. I fiddled around with it quite a lot, and came up with this 'perfect' setup. What I mean by this is that this will give you full flexibility, easy adding of modules and native "nice URLs". First of all, I'm using Apache as my webserver. If you're using something else, the .htaccess part might not work for you. Now, this RewriteRule is gold: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php What this does is redirect everything that can't be found on the hard drive to one main script (index.php). In this main script, we will parse some $_SERVER variables and determine what to load. The main script will be quite small, but it can be extended to do a lot of things. Most of the functionality will be the modules' responsibility. Here's the (basic) script: <?php # Dispatch requests to files in mod/ # Do initializing things here # like connect to your database, start a session etc. # Get the parts from the requested path $_ARG = explode('/', $_SERVER['PATH_INFO']); # If the root of the site was accessed (i.e., # set the default module to 'index' if (!$_ARG[0]) $_ARG[0] = 'index'; # Our modules will reside in the mod/ directory. If there's no file # for the current request, set the module name to 'not-found'. # (this will obviously crap out if there's not not-found.php in mod/) if (!file_exists('mod/' . $_ARG[0] . '.php')) $_ARG[0] = 'not-found'; # Include the file. It will have access to the $_ARG variable # to make its life easier. require_once 'mod/' . $_ARG[0] . '.php'; ?> As you can see, it loads the modules from the mod/ directory. Basically, will load article.php from the mod/ directory, which will use $_ARG[1] to determine what article to display. Isn't that extremely simple and useful? Let me know :-).

No comments:

Post a Comment