Fat-Free Framework – 2. Moving logic to controllers

Created at: October 6, 2016; Last update: October 7, 2016

In the previous tutorial (Fat Free Framework – 1. Installing Fat Free Framework…), we tested the installation of Fat Free Framework by creating a route that was calling an anonymous function when someone was accessing the application:

But if we do this for every “page” that someone access the main index.php file would become pretty large soon.

So why not create classes that would deal with different routes?

For starters, let’s change the line above with this and see if it works?

Now, if we visit the same page again, we will see that everything works fine.

As you can see, we can pass our route a controller (class) and a method by using the classic notation class->method.

All we have to do now is to move the class in its own file… So how do we do this?

So let’s create an “App/Controllers” directory and in it create a file named Homepage.php and put the class definition in it:

Now we will use the autoload system variable AUTOLOAD (https://fatfreeframework.com/quick-reference#AUTOLOAD). This allows us to define file that the framework will attempt to autoload at runtime. That means that if we pass it our app directory, any class called inside our application will be looked inside this directory.

So returning to our index.php we will ask the autoload functionality to take into consideration our app directory, by using the set() method to our instance:

Now, if we visit our website again we will see that… nothing happened… which is… good…

Let’s see the index.php again:

Now let’s see our App/Controllers/Homepage.php

See you next time.

Leave a Reply

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

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