So there are two basic components to the Controller part of Model-view-controller architecture. There's the .htaccess file which tells the server how to redirect the url request, and then there's index.php which contains hollowed out code, which will be filled in later.
First thing to realize is that there is just one page in an MVC setup. That's index.php. Everything else is an argument. What page? What data? what parameters? All arguments. Problem is no one wants to see index.php?page=page&table=table&p1=p1 in their address bar. It's ugly and bad for SEO. This is much nicer: site.com/page/table/parameter. It's easier to work with.
So let's start with the .htaccess file. This is the first stop for HTML requests when they hit your server. We want to tell the server to do what it's told, but if it can't find a corresponding page to serve, we want it to return the last segment of the url as an argument. Here's the code:
Options +FollowSymLinks
RewriteEngine On
# If requested resource does not exist as a file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?cmd=$1
That's it. If you want something more complex, you're in the wrong place. This will essentially turn site.com/p into site.com/index.php?cmd=p . Cool huh?
Next comes the index.php. You need to take the argument and use it to open an include in the index. Like so...
if ($_GET['cmd'])
{include_once("includes/sections/".$_GET[cmd].".php");}
else
{
echo "default content";
}
This essentially checks to see if there is a "cmd" identified in the URL and then opens an include with that name. If no argument is defined (just going to site.com) then it displays default content.
Voila - instant mvc. sort of. more later.
Friday, November 14, 2008
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment