bootstrap php code


, , ,

Let’s discuss how to bootstrap php code – funnel the HTTP requests into single php script, which handles the web application.

First thing you need to do is to add this rewrite code to your .htaccess file:

Options   FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_/\ ] )$ index.php?route=$1 [L,QSA]

If you plan to serve media files from php scripts and do other tricky things, your rewrite configuration can be more complex.

Nest step is implementing routing sheme. Now you should define routing layout. One of the most common options is /class/method/param1/…/paramX layout. One’s relatively easy to parse with php explode function. The router code breaks request uri to parts and retrieves the specific class, method and arguments.

if (empty($_GET['route'])) $route = 'index';
        else $route = $_GET['route'];
//Remember: default action should be defined in your app!
$route = trim($route, '/\\');
$parts = explode('/', $route);
foreach($parts as $part)
{
	$part = str_replace('-', '_', $part);
	$fullpath .= $cmd_path.$part;
	if (is_dir($fullpath))
	{
		$cmd_path .= $part.'/';
		array_shift($parts);
		continue;
	}
	if (is_file($fullpath.'.php'))
	{
		$class = $part;
		array_shift($parts);
		break;
	}
}

To process further, corresponding class should be loaded. You can implement class autoload function to find and load class from your classes directory. The simple code example, just remember to define CLASSDIR

function __autoload($class)
{
	$file = CLASSDIR.$class.'.php';
	if (!file_exists($file))
	{
		echo 'Requested module \''.$class.'\' is missing. Execution stopped.';
		exit();
	}
	require($file);
}

Calling class action with parameters

$class = new $class();
if (is_callable(array($class, $action)) == false)
{
	// function not found in controller, set it as index (or default action name) and send it to args
	array_unshift($args, $action);
	$action = 'index';
}
$class->$action($args);

It looks relatively easy to bootstrap php code, but remember you should check very carefully all incoming data to secure your application.

Firebug Extensions


Zend Studio Neon best PHP development tool


Zend Framework 1.0.2 Released


Great updates in PHP developers camp


PHP opcode caches – require_once is slow