Bootstrap PHP code

Simple code to funnel the HTTP requests in one single file, which handles the web application.

<?
// Simple bootstrap file PHP 5 (with no template engine)
// stop error reporting for curious eyes, should be set to E_ALL when debugging
error_reporting(0);
// name of folder that application class files reside in
define('CLASSDIR', 'site_src');
// application absolute path to source files (should reside on a folder one level behind the public one)
define('BASEDIR', @realpath(dirname(__FILE__).'/../'.CLASSDIR).'/');
// function to autoload classes (getting rid of include() calls)
function __autoload($class)
{
	$file = BASEDIR.$class.'.php';
	if (!file_exists($file))
	{
		echo 'Requested module \''.$class.'\' is missing. Execution stopped.';
		exit();
	}
	require($file);
}
// the router code, breaks request uri to parts and retrieves the specific class, method and arguments
$route = '';
$class = '';
$method = '';
$args = null;
$cmd_path = BASEDIR;
$fullpath = '';
$file = '';
if (empty($_GET['route'])) $route = 'index'; else $route = $_GET['route'];
$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;
	}
}
if (empty($class)) $class = 'index';
$action = array_shift($parts);
$action = str_replace('-', '_', $action);
if (empty($action)) $action = 'index';
$file = $cmd_path.$class.'.php';
$args = $parts;
// now that we have the parts, let's run a few more test and then execute the function in the class file
if (is_readable($file) == false)
{
	echo 'Requested module \''.$class.'\' is missing. Execution stopped.';
	exit();
}
// load the requested file
$class = new $class();
if (is_callable(array($class, $action)) == false)
{
	// function not found in controller, set it as index and send it to args
	array_unshift($args, $action);
	$action = 'index';
}
// Run action
$class->$action($args);

Usage

How to use it: 1. On your home directory create a folder (name it "site_src") to put the application's files inside it. 2. Inside the directory for the classes create a php code file and name it "index.php". 3. Paste the code below onto the file you have just created: <pre>class index { public function __construct() { } public function index($args) { echo 'This is the index page, shown by default to all requests that cannot be routed'; } }</pre> 4. Again create another class file in the same directory and name it "welcome.php" 5. Paste the code below onto the file: <pre>class welcome { public function __construct() { } public function index($args) { // redirects to test() $this->test($args); } public function test($args) { if (isset($args[0])) echo $args[0]; if (isset($args[1])) echo ' '.$args[1]; } }</pre> 6. Add this rewrite code to your .htaccess file: <pre>Options FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9-_/\ ] )$ index.php?route=$1 [L,QSA]</pre> Note that this rewrite allows only specific characters in the URI. 7. Grab the code from snippet and paste it in the index file (index.php) inside your public_html directory. 8. Test the bootstrap code by surfing to your site: http://www.example.com/welcome/test/hello/steve/


Comments

guest
Posted on 06.02.2012 13:13

Nope: Shorttags will stay forever.

guest
Posted on 07.07.2011 20:54

ellisgl, wiki said about PHP6:
New features: traits, array dereferencing, closure $this support, JsonSerializable interface, "<?=" no longer requires 'short_open_tag' set to ON

http://en.wikipedia.org/wiki/PHP

I don`t know why it written there but I can imagine the reason. I think it's not a fake. ;-)

guest
Posted on 03.05.2011 21:12

Is this still active

guest
Posted on 09.10.2010 12:20

Nice

guest
Posted on 13.09.2010 07:07

ellisql: PHP6 will still allow <? short tags. Support for ASP ones

steve
Posted on 17.12.2008 19:57

Hi denki,
of course you can. You can use a template class to pass variable so they will
be available to the "html" php page.
The simplest working template class for this code would be:


class template
{
private $vars = array();
function __construct() {}
function __get($key) {return $this->$vars[$key];}
function __set($key, $var) {$this->vars[$key] = $var;}
function show($name)
{
$path = BASEDIR.output/'.$name.'.php';
if (!file_exists($path))
{
echo 'missing template file';
exit();
}
foreach ($this->vars as $key => $value) $$key = $value;
require($path);
}
}

Where "output" is the folder with the template. So in the welcome.php class for
example you can instantiate the template class, run the page code and then
assign variables to the template file:

class welcome
{
public function __construct()
{
}
public function index($args)
{
// redirects to test()
$this->test($args);
}
public function test($args)
{
$t = new template();
$t->arg1 = args[0];
$t->arg2 = args[1];
$t->show('welcome');
}
}

And the "html" (template) php page will have something like this:
<?=$arg1;?>
<?=$arg2;?>

If the paths are fine doing it like this it will work.

denki
Posted on 17.12.2008 14:09

Hi,
I wonder if it's possible to use variables inside the application's files (welcome.php). And have them interpreted in the main file.

I want to change a page title tag with any new URL for example. Or is "echo" the only way to generate output?

Thanks
Denki

steve
Posted on 27.10.2008 22:43

Yes, spl_autoload would be good if you are mixing libraries.

ellisgl
Posted on 27.10.2008 17:54

Here's my refactoring..


/**
* Simple bootstrap file PHP 5 (with no template engine)
*/

// stop error reporting for curious eyes, should be set to E_ALL when debugging
error_reporting(0);

// name of folder that application class files reside in
define('CLASSDIR', 'site_src');

// application absolute path to source files (should reside on a folder one level behind the public one)
define('BASEDIR', @realpath(dirname(__FILE__).'/../'.CLASSDIR).'/');

// Class to autoload classes (getting rid of include() calls)
class AutoLoader
{
public static function Load($Class)
{
$File = BASEDIR.$class.'.php';

if(is_readable($File))
{
require($File);
}
else
{
die('Requested module "',$Class,'" is missing. Execution stopped.');
}
}
}

spl_autoload_register('AutoLoader::Load');

// the router code, breaks request uri to parts and retrieves the specific class, method and arguments
$route = '';
$class = '';
$method = '';
$args = null;
$cmd_path = BASEDIR;
$fullpath = '';
$file = '';

if(empty($_GET['route']))
{
$route = 'index';
}
else
{
$route = $_GET['route'];
}

$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;
}
}

if(empty($class))
{
$class = 'index';
}

$action = array_shift($parts);
$action = str_replace('-', '_', $action);

if(empty($action))
{
$action = 'index';
}

$file = $cmd_path.$class.'.php';
$args = $parts;

// now that we have the parts, let's run a few more test and then execute the function in the class file
if(is_readable($file) === false)
{
die('Requested module "',$class,'" is missing. Execution stopped.');
}

// load the requested file
$class = new $class();

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

// Run action
$class->$action($args);

ellisgl
Posted on 27.10.2008 17:30

Also I would use spl_autoload_register instead of the __autoload directive

ellisgl
Posted on 27.10.2008 17:27

Note: Stop using short tags. Turn short tags off in your ini file. PHP 6 will no longer support it, also if you need to deal with XML documents, you have to do thing to prevent the PHP engine from trying to parse it as a PHP file.

Add your comment