Tutorial

How To Use the Fat Free PHP Framework

Published on March 7, 2014
author

Marco Troisi

How To Use the Fat Free PHP Framework

Background


Fat Free Framework is a PHP micro-framework that was started in 2009 by Bong Cosca. Following a minimalistic approach, it tends to avoid adding code and structure that are not strictly necessary, while focusing on what really matters.

Why a micro-framework?


This type of minimalistic design is common amongst the so-called micro-frameworks, of which PHP offers a wide choice. Other popular micro-frameworks are: Slim (PHP), Sinatra (Ruby) and express.js (node.js). These frameworks usually have a few advantages like, for example:

  • Being extremely lightweight (Fat Free only amounts for roughly 55kb)

  • Having a gentle learning curve, allowing developers to focus almost exclusively on what matters by not having to change their coding style.

  • Offering many of the functionalities that mature, full-fledged frameworks would usually have.

It goes without saying that choosing a micro-framework like Fat Free is not always the best choice. For big projects where a team of people is expected, a more opinionated and structured framework such as Yii or Zend would likely be a better choice.

Set up a new project with Fat Free


The first steps: downloading the framework unzipping the file within your project’s root folder.

Fat Free only runs on PHP 5.3 and higher. If you’re not sure of the version that you’re currently using, you can check by typing:

/path/to/php -v

After having established that the environment where you’re developing is the right one, create a file called index.php, which is going to be your project bootstrap file. On the first line, include Fat Free:

// FatFree framework
$f3 = require ("fatfree/lib/base.php"); 

Then, you’ll have to tell your application if you’re in development or in production mode by setting this variable:

// Set to 1 when in development mode, otherwise set to 0
$f3->set('DEBUG', 1);

Database


And of course, you’ll have to set up a database connection. Assuming you’re using MySQL:

// MySql settings
$f3->set('DB', new DB\SQL(
    'mysql:host=localhost;port=3306;dbname=mydatabase',
    'dbuser',
    'dbpassword'
)); 

Or, if you prefer using SQLite:

$db=new DB\SQL('sqlite:/var/www/myproject/db/database.sqlite'));

Queries


A simple query can be called by typing:

$result = $db->exec('SELECT field FROM table WHERE id = "1"');

Or, if you like it, you can use Fat Free’s built-in ORM. The query above would become something like this:

$table = new DB\SQL\Mapper($db, 'table');
$table->load(array('id=?', '1'));
$result = $table->field;

With the DB\SQL\Mapper function, you’re essentially “mapping” a table that is already in your database. Should you instead need to add a new record in your table, you’ll have to type:

$table = new DB\SQL\Mapper($db, 'table');
$table->field = "Here is a value";
$table->save();

Notice: You won’t be able to alter your table using ORM.

Giving a structure to your project


Since Fat Free is a micro-framework, it doesn’t come with a ready-to-use structure for your project, thus you’ll have to create it by yourself. An example of a structure for your project could be:

- api
-- models
- css
- js
- template
- views
- index.php

But of course you’ll be entirely free to use the structure that you love. That’s the best thing about using a non-opinionated framework.

Autoloading


In order to avoid having to include all your classes into your project, Fat Free allows you to use the autoloading feature, which is a way to include classes only at the time you really need them. So, to invoke all our classes, we only need to type:

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

In our case, api/models/ will clearly be the location where we save all our Model classes. When you invoke a class (e.g. $myClass = new myClass()), Fat Free will automatically look for a file called in the same way (myClass.php) within the autoloaded location.

Routing


The next interesting thing is the way Fat Free manages our application’s routing. This is how we define routing to our home page:

$f3->route('GET /',
    function() {
        echo 'This is my Home Page!';
    }
);

Notice the GET attribute there. If needed, it can be replaced with POST, or even with GET|POST, should you need both of them. And then there’s obviously a function that defines what that page should do. You can of course manage different parameters too, using this syntax:

$f3->route('GET|POST /post/@id',
    function($f3) {
        echo 'Post #'.$f3->get('PARAMS.id');
    }
);

As you can see, everything preceded by @ will be considered a variable parameter.

Templating and Views


Fat Free gives you the ability to have your template and views. To include your template/view in a route command, just write:

$f3->route('GET /',
    function($f3) {
        // Instantiates a View object
        $view = new View;
        // Header template
        echo $view->render('template/header.php');
        // This is a variable that we want to pass to the view
        $f3->set('name','value');
        // Page view
        echo $view->render('views/index.php');
        // Footer template
        echo $view->render('template/footer.php');
    }
);  

In order to set variables to be passed to a view, you can use the $f3->set('nameVariable', 'value') function, and then invoke that same variable into the view (e.g. views/index.php) by typing `<?php echo $nameVariable; ?>. It’s really simple.

In conclusion, these are probably the most useful features that you’ll need when developing your first application with Fat Free framework. Should you need more of them, you can always refer to the official documentation.

<div class=“author”>Submitted by: <a href=“http://www.marcotroisi.com/”>Marco Troisi </a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Marco Troisi

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
10 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Set to 1 when in development mode, otherwise set to 0

I think better advice would be to use php’s more meaningful built-in ‘true’ / ‘false’ for this.

$f3->set('DEBUG', true);

or

$f3->set('DEBUG', false);

Personally I wouldn’t use a framework that aims to copy a lot of the early work of Slim v1/v2 and Laravel. The fastest and most performant framework to date is Lumen.

A think a new section that would help a lot of people would be on pagination since in the docs it follows a section on crud and it seems to use pagination you have to follow getting records using a crud style. Personally I prefer this style $result = $db->exec(‘SELECT field FROM table WHERE id = “1”’);

By the way if id is an int should that not be WHERE id=1’);

@Marco cheers will check that out

andy brookes

HI @andybrookestar, while PHP’s native mail() will work most of the times, and Fat Free’s SMTP() is certainly decent, I would also suggest using Swift Mailer, a rock solid library that I have been using for years now.

Marco

cheers Kamal

thats exactly what I did and its now working :

http://www.accra-guesthouse.com/contact_us ; I might pursue smtp later I read doing it that way is heavy on web resources.

The smtp syntax for a web domain is:

$smtp = new SMTP (mail.domain.com , 25 , $scheme, $user, $pw );

scheme I think you can leave out. im using for my web hosting user and password is going to be the user & password for my hosting account ?

See (http://fatfreeframework.com/smtp)

mail ($to, etc …) will do for now. All in all i’m likeing fat free a lot and have managed to use my own class for populating the meta tags in the header. Each view results in different relevant keywords in the header , which is used for all views.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
May 13, 2014

@andybrookestar: You can simply use <a href=“http://php.net/manual/en/function.mail.php”>PHP’s mail() function</a>. As far as I know, Fat Free does not come with a mail library.

I would like to use a simple contact form in web page using fat free (a view) <input type =“text” etc …

and get the message sent to my own email address with codeigniter you just use:

$this->email->from(‘webmaster@ginbrookes.tk’,‘andy’); $this->email->to($theirEmail); $this->email->subject($subject); $this->email->message($message ); $this->email->send();

I read somewhere fat free uses smtp ; any idea of the equivalent of the above?

Andrew SB
DigitalOcean Employee
DigitalOcean Employee badge
May 6, 2014

@andybrookestar: Thanks for sharing! That’s helpful.

ok this seems to load any page using url:

http://localhost/fatfree/sompage

$f3->route(‘GET /@page’, function($f3) { $view = new View; $page = $f3->get(‘PARAMS[“page”]’); echo $view->render(“ui/{$page}.htm”); } );

The next thing is to populate metatags with keywords relevant to page

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more