Routing Practice and Event Handlers with Fat-Free Framework

In my previous post we successfully created a hello world example with Fat-Free (F3). Now we will use that example to practice basic routing and Event Handlers on F3.

First: Routing

Currently our index.php (locate at:: web_root/helloworld/index.php) file has only few lines. Like below::

<?php

$f3 = require('lib/base.php');

$f3->route('GET /',
    function() {
        echo 'Hello, World!';
    }
);

$f3->run();

we will add our all routing code block before last line “$f3->run();”.
if you access http://localhost/helloworld/ we can see “Hello, World!” output in your browser. here we already did a routing.

if route function first param ‘GET /’ telling that if the request is using GET method and for root url / then it will execute that param. So the first parameter is the route that you’re “registering” with the router. The second parameter is the function containing the logic for that route.

Now practice something::

In line 5 change the 1st param to ‘/’ and try to browse http://localhost/helloworld/, you should get a “Invalid routing pattern: /” error message. so it means we have to provide the request method name in 1st param. Fix it to ‘GET /’. now our example is working.

we will add a new routing, just put the below code block after line 9.

$f3->route('GET /home',
    function() {
        echo 'This is our home page.';
    }
);

http://localhost/helloworld/home, you will get out “This is our home page.”.

Route to another page “About”, just add below code block to your index.php and browse http://localhost/helloworld/about::

$f3->route('GET /about',
    function() {
        echo 'This is the page for about me.';
    }
);

Add route to another page “Apple”::

$f3->route('GET /apple',
    function() {
        echo "We have apples.";
    }
);

So URL for Apple page is http://localhost/helloworld/apple. now we want to pass a token to this URL that how apples we have. so modify this routing block little bit like below::

$f3->route('GET [email protected]',
    function($f3) {
        echo "We have {$f3->get('PARAMS.count')} apples.";
    }
);

Browse by URLs::
1) http://localhost/helloworld/apple/3, output = We have 3 apples.
2) http://localhost/helloworld/apple/good, output = We have good apples.

Another way to get the URL token is::

$f3->route('GET [email protected]',
    function($f3,$params) {
        echo $params['count'].' cars.';
    }
);

We can use the asterisk (*) to accept any URL after the /car route – if we don’t really care about the rest of the path:-

$f3->route('GET /car/*',
    function() {
        echo 'We have enough cars.';
    }
);

If we want to redirect to another page then the route will be::

$f3->route('GET|HEAD /go_google',
    function($f3) {
        $f3->reroute('http://www.google.com');
    }
);

If we access http://localhost/helloworld/go_google then it will redirect to us to google.com page. So “reroute” is doing redirect for us. In first param of route function you can see that we used both GET and HEAD request, so this way we can use GET, POST and HEAD requests.

This is now all for basic routing. You can get the full code here:: http://codepad.viper-7.com/B2ESrO

Next we will learn some advance ways of routing.

Now we will separate our routing logic to function. Add below lines before last line “$f3->run();”.

$f3->route('GET /about','about');
function about() {
    echo 'about page';
}

Here we separated the routing logic to “about” function and in “route” function we added the function name as call back function. Access http://localhost/helloworld/about to get the output.

To get URL token add below code block::

$f3->route('GET [email protected]','comments');
function comments($f3) {
    echo "We have {$f3->get('PARAMS.count')} comments.";
}

Access http://localhost/helloworld/comments/5, output will display. But if you access http://localhost/helloworld/comments/ without token then you will get error message. This URL is correct but we have no routing in our index.php file.
So we have add routing for this request URL. The complete code block for this “comments” request is::

$f3->route('GET [email protected]','comments');
$f3->route('GET /comments','comments');
function comments($f3) {
    echo "We have {$f3->get('PARAMS.count')} comments.";
}

I think, this is F3 limitation that we have to declare both way but it can be solve by (‘GET /comments/*’ and ‘GET /comments/?’).

Another ways to get the URL token::

$f3->route('GET /tags/*','tags');
function tags($f3,$params) {
    echo "We have {$params['1']} tags.";
}

$f3->route('GET /posts/*','posts');
function posts($f3) {
    echo "We have {$f3->get('PARAMS.1')} posts.";
}

Now routing with OO ways::

class MyPages {
    static function home() {
        echo 'this is home page.';
    }

    function cows($f3) {
        echo "there are {$f3->get('PARAMS.1')} cows.";
    }
}

$f3->route('GET /home','MyPages::home');
$f3->route('GET /cows/*','MyPages->cows');

In above example you can see that F3 allows static function call in routing.

Dynamic Route Handlers

Create a new class “Animal” and that two route handlers like bellow::

class Animal {
    function dog() {
      echo "This is dog's action.";
    }

    function tiger() {
        echo "This is tiger's action.";
    }

    function cat($f3) {
        echo "This is {$f3->get('PARAMS.color')} cat.";
    }
}

$f3->route('GET [email protected]','Animal->@action');
$f3->route('GET [email protected][email protected]','Animal->@action');

So now you can browse following ways ::
1) http://localhost/helloworld/animal/dog
2) http://localhost/helloworld/animal/tiger
3) http://localhost/helloworld/animal/cat/red

Advance routing index.php file will be found at http://codepad.viper-7.com/W57JcS.

Second: Event Handlers

If we want to improve the flow and structure of controller classes, F3 has two routing event listeners.

Now remove all codes from index.php. and create a “Animal” class and define a routing, the index.php will look like below::

<?php

$f3=require('lib/base.php');

class Animal {
    function dog() {
      echo "This is dog's action.<br/>";
    }

    function beforeRoute() {
       echo "START::<br/>";
    }

    function afterRoute() {
        echo "END::<br/>";
    }
}

$f3->route('GET [email protected]','Animal->@action');

$f3->run();

If you access this http://localhost/helloworld/animal/dog, you will see output like below::

START::
This is dog's action.
END::

So here, HTTP request for “animal/dog”, F3 will looks for a method “beforeRoute()” in this class “Animal”. This function will execute first if it found. Then F3 will execute “dog()” method. After execute “dog()” F3 will look for “afterRoute()” method, again if this method found then F3 will execute this at last.

I am a student of Web Application Development courses at Google University.
4 comments on “Routing Practice and Event Handlers with Fat-Free Framework
  1. When I try to add a second route, the browser shows a 404 Not found error… do you have any idea why is this happening? Thanks in advance.

    • Solved! If someone have the same issue, just move the .htaccess to your folder (in this tutorial, helloworld).

Leave a Reply

Your email address will not be published. Required fields are marked *