views:

140

answers:

5

In the last couple of websites I made, I implemented a kind of MVC-style controller, I think.

I used mod_rewrite to send everything through index.php, so the url became a querystring.

It worked, but I'm wondering if it's a bit hacky, or just the accepted way of doing things. Is there a better way? I don't want a framework, I want to learn to do it myself.

+1  A: 

That's the way I accomplished it. I then created a dispatch table that new, based on URL, which controller to instantiate and which dispatch to run.

Myles
+2  A: 

Passing everything through a single point of entry, e.g. index.php is not MVC, it is the FrontController Pattern. This goes well with MVC though. See my related answer here.

Apart from that, why not check out some of the frameworks around to learn how they do it. Doesn't mean you have to use them, just look at their code and adapt for your own framework.

Gordon
+6  A: 

Try my smallest framework in the world.

<?php
$g=$_GET;$c=@$g['c']?$g['c']:'Home';
if(!@include"c/$c.php")die('fail');
$m=method_exists($c,$m=@$g['m'])?$m:'index';
$o=new$c();$o->$m($g);

That goes in index.php and your controlls are Blog.php in ./c/Blog.php.

class Blog {

    function index()
    {
        echo "Hello world";
    }

    function otherpage()
    {
        echo "ZOMG!";
    }

Made mainly as a joke, as I wanted to make a framework that could fit in a tweet, but the basic logic is there ;-)

Phil Sturgeon
maked my day :D +1
yoda
That is truly awesome :)
Skilldrick
Phil Sturgeon
Article complete: http://philsturgeon.co.uk/news/2009/12/Twiny-Framework-the-framework-small-enough-to-tweet
Phil Sturgeon
+1  A: 

How about learning to do it yourself, but still use a framework ? Either way, take a look at an open source framework like Symfony or CMS apps like Wordpress, Jommla! etc, and you will find that they all use mod_rewrite to set things off.

sjobe
+1  A: 

Most PHP frameworks make use of mod_rewrite do accomplish the same objective, and it's the only way to suppress index.php and make the urls more friendly, in a segmented way.

I'd say you're in the right path.

That method you used is called FrontController Pattern, and it's used by those frameworks as well, to go along with the MVC pattern.

If you care for a suggestion, I'd recommend you to make every request pass through each page controller, extending a base controller, since every site has some base data structures that you will probably need to use in every page, such as templates and session control.

yoda