AS for an approach I would use a method similar to CodeIgniter or other MVC frameworks ( but simpler ).
So first you have to devise a schema, what I mean by that is something like this
www.yoursite.com/index.php/{controller}/{method}/args ...
Then you would build a router to go parse the url. I can write you one but it will take a minute.
UPDATE
You can find it on my github page here
But for refrence here is the code:
SimpleRouter.php
/**
* A simple 1 level router
*
* URL schema is http://example.com/{controller}/{method}/{args ... }
*
* @author ArtisticPhoenix
* @package SimpleRouter
*/
class SimpleRouter{
/**
* should be the same as rewrite base in .htaccess
* @var string
*/
const REWRITE_BASE = '/MISC/Router/';
/**
* path to controller files
*
* @var string
*/
const CONTOLLER_PATH = __DIR__.'/Controllers/';
/**
* route a url to a controller
*/
public static function route(){
//normalize
if(self::REWRITE_BASE != '/'){
$uri = preg_replace('~^'.self::REWRITE_BASE.'~i', '',$_SERVER['REQUEST_URI']);
}
$uri = preg_replace('~^index\.php~i', '',$uri);
$uri = trim($uri,'/');
//empty url, like www.example.com
if(empty($uri)) $uri = 'home/index';
//empty method like www.example.com/home
if(!substr_count($uri, '/')) $uri .= '/index';
$arrPath = explode('/', $uri);
$contollerName = array_shift($arrPath);
$methodName = array_shift($arrPath);;
$contollerFile = self::CONTOLLER_PATH.$contollerName.'.php';
if(!file_exists($contollerFile)){
//send to error page
self::error404($uri);
return;
}
require_once $contollerFile;
if(!class_exists($contollerName)){
self::error404($uri);
return;
}
$Controller = new $contollerName();
if(!method_exists($Controller, $methodName)){
self::error404($uri);
return;
}
if(!count($arrPath)){
call_user_func([$Controller, $methodName]);
}else{
call_user_func_array([$Controller, $methodName], $arrPath);
}
}
/**
* call error 404
*
* @param string $uri
*/
protected static function error404($uri){
require_once self::CONTOLLER_PATH.'home.php';
$Controller = new home();
$Controller->error404($uri);
}
}
Default Controller home.php
/**
*
* The default controller
*
* @author ArtisticPhoenix
* @package SimpleRouter
*/
class home{
public function index($arg=false){
echo "<h3>".__METHOD__."</h3>";
echo "<pre>";
print_r(func_get_args());
}
public function otherpage($arg){
echo "<h3>".__METHOD__."</h3>";
echo "<pre>";
print_r(func_get_args());
}
public function error404($uri){
header('HTTP/1.0 404 Not Found');
echo "<h3>Error 404 page {$uri} not found</h3>";
}
}
2nd Controller (example) user.php
/**
*
* An example users router
*
* @author ArtisticPhoenix
* @package SimpleRouter
*/
class user{
public function index(){
echo "<h3>".__METHOD__."</h3>";
}
public function login(){
echo "<h3>".__METHOD__."</h3>";
}
}
Rewrite (remove index.php) .htaccess
RewriteEngine On
# For sub-foder installs set your RewriteBase including trailing and leading slashes
# your rewrite base will vary, possibly even being / if no sub-foder are involved
RewriteBase /MISC/Router/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Finally index.php
require_once __DIR__.'/SimpleRouter.php';
SimpleRouter::route();
I went with a static
call to the router just to keep things simple, this way no instance is needed of the class which only has 2 methods (1 public) anyway.
I built it as a single level router, what I mean by that is that you cannot put controllers in sub-folders, such as Controllers/user/home.php
instead of just Controllers/user.php
. This should be fine for small to medium sized sites, but for a vary large site it may be desirable to nest the controllers. However this adds a bunch of complexity to it.
The advantage of this way, instead of individually creating the routes should be obvious. You shouldn't have to touch the code as long as the route (the url) follows the simple schema I outlined. This also allows you organize the sections of your site in their own files by functionality. For example take the user.php
controller. Would let you put all that functionality in one place, such as the login, profile, logout pages etc...
If you were to add a member.php
controller you can put all the stuff that you only want to show to logged in users there. And then in the __construct
method of that controller you check if the current session is logged in and it covers all methods for that file.
The url schema is this http://example.com/{controller}/{method}/{args ... }
. But you can also use urls like this http://example.com/index.php/{controller}/{method}/{args ... }
. I'm using Mod Rewrite to allow for the removal of the index.php
in the URL, so if you don't have that then you have to put index.php
in the URL ( or remove it by some other means )
REWRITE_BASE On my local test server I just place everything in it's own folder as I am to lazy to setup virtual hosts. So you would want to change this constant, and the matching .htaccess, value to be whatever your sub folder is ( maybe nothing ). I just left it here for example of how to use it within a sub-folder.
Lastly, this is the C
in traditional MVC architecture. You should avoid doing what is called "Business logic" in the controllers, you should also avoid outputting HTML directly from the controller (although I did this in the examples). Instead of outputting the HTML, I would suggest using a template engine like Blade
or Twig
there are many of these freely available. Think of a Controller like the "Glue" that joins the "Model (business logic)" to the "View (template)". Business logic would be like a User class (uppercase U like a noun, not lowercase as in our user controller) that handles the Database functionality for users. So instead of putting that code right in the Controller you would build a "User Model" and import that into the controller. This is the "Right Way" to do it, but of course it adds some complexity up front, but you will find later on the organization of it to far outweigh that in time savings.
Now some examples
404 errors (and missed routes):
http://example.com/foo
routes to home::error404()
and outputs <h3>Error 404 page foo/index not found</h3>
http://example.com/home/foo
routes to home::error404()
and outputs <h3>Error 404 page home/foo not found</h3>
Default Home page:
http://example.com/
routes to home::index()
http://example.com/index.php
routes to home::index()
http://example.com/home
routes to home::index()
http://example.com/home/index
routes to home::index()
http://example.com/home/index/hello
routes to home::index('hello')
http://example.com/home/index/hello/world
routes to home::index('hello','world')
As it stands you have to put the full path in for arguments for home, the above code could be changed to account for this but it has some repercussions for missing pages. Basically any missing page would become an argument of the controller. So if you had http://example.com/user/foo
it would call user::index('foo')
if that was done. Of course this too can be accounted for but the complexity starts to stack up.
http://example.com/home/otherpage
routes to home::otherpage()
but issues a warning for missing argument.
http://example.com/home/otherpage/hello
routes to home::otherpage('hello')
http://example.com/index.php/home/otherpage/hello
routes to home::otherpage('hello')
If you look: home::index($arg=false)
defines a default, where this method does not. So this method requires an argument. The rest of this should be pretty self explanatory.
Second Controller user example:
http://example.com/user
routes to user::index()
http://example.com/user/index
routes to user::index()
http://example.com/user/login
routes to user::login()
The rest of this is pretty much the same, I just wanted to show how to organize the controllers by functionally for the site.
I should note that this can handle an unlimited number of arguments following the {method}
in the url.
Enjoy!
In my .htaccess file i have FallbackResource index.php
can you share some of the .htaccess rules you use? Be sure to remove anything you don't want public like the host for example you could dowww.mysite.com
instead of the real name.