Fat-Free Framework – 7. Enter the Views. How to separate logic from presentation in F3

Up until now we’ve done our tests by echoing to the browser window the variables. Of course, this was only to do our tests and to see if what we do is ending well or not.

But now we should talk about the Views in MVC. Do you remember the global variables that Fat-Free Framework is using extensively in what it names the Hive? Well… Among these global variables there exists one named UI (from user-interface?). This variable tells the framework where it can find the views in case these views are called.

So, let’s create a directory named “Views” inside our “App” directory, and then call the setup.cfg (“App/Config”) and add a new line where we define this UI variable:

[globals]
DEBUG=3
AUTOLOAD=App/Controllers/
UI=App/Views/

Now let’s create a view inside our new Views directory, named HomepageView.php, and try to output something:

<?php
echo 'hello from index';

Now, going back to “App/Controllers/Homepage.php“, we do the following:

<?php

class Homepage {

  function index(){
    $view=\View::instance();
    echo $view->render('HomepageView.php');
  }
}

Now if we visit the homepage of our site, everything looks ok. But how do we pass variables to the view? We pass them as parameters inside our render() method, inside an array. As a test, let’s return to Homepage.php and write:

<?php

class Homepage {
    function index(){
        $f3=\Base::instance();
        $view=\View::instance();
        $data = array();
        $data['name'] = 'avenirer';
        $data['url'] = $f3->alias('the_contact_page','who=avenirer');
        echo $view->render('HomepageView.php','text/html',$data);
    }
}

Now, moving to our HomepageView.php, we write:

<?php
echo 'hello from index'.'<br />';
echo '<a href="'.$url.'">'.$name.'</a>';

Super… Meet 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.