Fat-Free Framework – 2. Moving logic to controllers

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:

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

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?

class Homepage {
  function index(){
    echo 'hello from index';
  }
}

$f3->route('GET /', 'Homepage->index');

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:

class Homepage {
  function index(){
    echo 'hello from index';
  }
}

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:

$f3->set('AUTOLOAD','App/');

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

Let’s see the index.php again:

<?php
require_once('vendor/autoload.php');

$f3 = Base::instance();

$f3->set('AUTOLOAD','App/Controllers/');

$f3->route('GET /', 'Homepage->index');

$f3->run();

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

class Homepage {

  function index(){
    echo 'hello from index';
  }
}

See you next time.

Leave a Reply

Your email address will not be published.

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