Fat-Free Framework – 5. Returning to routes and how to work with them

Created at: October 13, 2016; Last update: October 13, 2016

Fat-Free Framework has a good routing engine. So let’s see what we can do with it.

For starters let us assume that the contact page would need to receive a parameter yoursite.com/contact/avenirer

If you visit that address you should get a nice 404.

How do we get that “avenirer” part inside our method, and not be redirected to a 404?

Going to our routes.cfg, we write the following line just before the contact route:

Now if we visit the same url, we see that everything went smooth, as the framework is returning our index() method of the Contact controller. But how do we retrieve “avenirer” inside our method?

The framework is saving the “@who” as a variable inside our global parameters (actually it is a key of the PARAMS array), and we can access it by calling $f3->get(‘PARAMS.who’). So let’s echo this:

Nice. Isn’t it? Now how about more than one url segment? Well… You can name the url segments inside the routes:

Also, if you don’t know how long the segments will be, you can use the wildcard (*). So, if for example you have an url like: yoursite.com/contact/avenirer/bymail/orwhatever/andwhatever

You could write something like this route:

Now you can retrieve the whole url by writing:

Defining and using named routes

When defining a route we can give that route a name. “Now, why would you go and do that?” you might say. Let’s think about it for a moment… If we have inside our views links that point to a certain page, and then we decide to change the url to that page, we would have to go in each view and change those links. Now, if we have a name for that route we can use that name inside our views to call for that particular route, wherever it may send us.

So, in our views, instead of using a “hard-coded” url, we can call the route’s name. Let us first define a named route inside our routes.cfg:

Now, in the views you can use it by calling the alias() method

If you need to pass one parameter to the named url (assuming the route is defined like this: GET @the_contact_page:/contact/@who/=Contact->index ), you write:

Although we will talk later about the templating engine (yes, Fat-Free Framework also has a templating engine), we should also mention the equivalent of the above:



Leave a Reply

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

No spam? * Time limit is exhausted. Please reload CAPTCHA.