I am working on a personal project based in PHP and MySQL, and I am doing a bit of research and playing around with rewrites. Say I have a site...
http://www.myDomain.com/
And I want to have an index.php, or bootstrap, in the root of the domain. So if you access...
http://www.myDomain.com/admin/
It will still load from the index.php in the top level of the domain, which handles the parsing and loading of configuration files, and redirecting the user to the correct location, making pretty links along the way.
Where should I start in my research and education on this? I'm at a loss somewhat. Thank you for your time :)
Update:
Sounds like I do want to move towards a MVC system with a front controller. Any good references on writing my own MVC framework (would be very basic). I honestly don't want to pull in the Zend Framework at this time (would bulk it up a lot!)
Basically, you rewrite any incoming request to your index.php
. Here's an example .htaccess
from the Kohana framework:
# Turn on URL rewriting
RewriteEngine On
# Protect application and system files from being viewed
# RewriteRule ^(application|modules|system) - [F,L]
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT,L]
So your example of would be routed to index.php/admin
. Then you can look at $_SERVER['REQUEST_URI']
to determine what to do next.
A relatively common pattern would be to use the first segment of the URI
as the controller, and the second as the method. So for example:
$segments = explode($_SERVER['request_uri'], '/');//array('admin')
if(isset($segments[0]))
{
$class = $segments[0].'_controller';//'admin_controller
if(isset($segments[1]))
$method = $segments[1];
else
$method = 'index';
}
else
{
$class = 'index_controller';
$method = 'index';
}
$controller = new $class;
$controller->$method();
That code is by no means production ready, as it would die a fiery death, if for example the user visited a URL for a non-existent controller. It also doesn't do nice things like handle arguments. But it's kind of the idea behind how a PHP MVC framework operates.
By the way, another name for what you're calling bootstrap is front controller. You can google that term to find a lot more information about the pattern.
You will need to look at configuring your .htaccess
to internally rewrite all requests to your bootstrap file, which may be index.php
Kohana uses this to do it
# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
You can then access $_SERVER['REQUEST_URI']
to begin routing requests to controllers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With