The Perl community has long laid claim to the motto "There's more than one way to do it". As a long time member of the PHP community, I often wonder whether our motto should be, "There's more than ten ways to do it." The number of competing PHP projects can be staggering at times, as is evidenced by the ten lightweight frameworks I introduced in last year's article, Top 10 Lightweight Frameworks for PHP Development. While sorting through such a broad selection of solutions can at times be overwhelming, the advantage is that with some patience you will eventually come across a solution which perfectly suits your particular tastes.

While I argue that you should consider using a framework for practically every new project you tackle, precisely which framework you choose isn't so clear-cut. For instance, robust solutions such as the Zend Framework and symfony offer every imaginable feature one could want in a framework, but come at the cost of a fairly significant learning curve. If you're keen to start capitalizing upon the great framework-oriented features you've heard so much about but aren't yet ready to invest the significant time required to master one of the more involved solutions, consider investigating one of the lightweight solutions such as the PHP Fat-Free Framework.

In this article I'll show you just how easy it is to get started building Web sites using this deceptively tiny (55kB) framework.

Incidentally, Fat-Free takes advantage of several features available only to PHP 5.3.0 and newer, therefore if you haven't yet taken the time to upgrade your PHP installation, you'll need to do so in order to follow along with the examples found in this tutorial.

Introducing the PHP Fat-Free Framework

The PHP Fat-Free Framework manages to pack an incredible set of features into an incredibly small code base, offering native support for caching, bandwidth throttling, and a template engine. A suite of plugins further enhance Fat-Free's capabilities, providing developers with the opportunity to integrate databases including MongoDB, process forms, generate CAPTCHAs, and manage user authentication, among other features.

To follow along with the ensuing examples, download Fat-Free and place the unarchived files within a directory accessible by your Web server. You'll also need to rename the htaccess file included with the download, placing the required period in front of the file name (.htaccess). You'll also need to enable Apache's mod_rewrite module if it isn't already enabled, as Fat-Free uses mod_rewrite to map the website's various routes to their respective handlers. I also suggest renaming the sample index.php file to something like index.php-orig. The index.php file plays a special role within Fat-Free websites, as it is where you'll define the website routes and associated route handlers.

Using Clean URLs with PHP Fat-Free

Fat-Free might be used to implement a website consisting of solely static HTML pages and requiring little more than clean URLs. For instance, the following index.php file defines three routes (homepage, /about, and /contact), rendering a static page in response to each respective route request. Notice the use of PHP 5.3's powerful anonymous function feature, which can significantly reduce the amount of code you'd have to otherwise write.

<!--p

require_once 'F3/F3.php';

F3::route('GET /about',
  function() {
    echo F3::serve('pages/about.html');
  }
);

F3::route('GET /contact',
  function() {
    echo F3::serve('pages/contact.html');
  }
);

F3::route('GET /', 
  function() {
    echo F3::serve('pages/index.html');
  }
);

F3::run();

Save this file in your project home directory as index.php, create a directory called pages which contains the three respective HTML pages, and you're done.

Creating Dynamic Pages with PHP Fat-Free

Of course, a framework's advantages really become apparent when creating dynamic pages. You can identify parts of a route as being dynamic by defining a token within the route definition. For instance, the previous index.php file can be refactored to define a dynamic token parameter called @page which could subsequently be used to retrieve the desired page:

<!--p

require_once 'F3/F3.php';

F3::route('GET /', 
  function() {
    echo F3::serve('pages/index.html');
  }
);

F3::route('GET /@page',
  function() {
    $page = F3::get('PARAMS["page"]');
    echo F3::serve("pages/{$page}.html");
  }
);

F3::run();

Building Page Templates with PHP Fat-Free

If you were building a database which contained a great deal of information your favorite video games then it certainly won't make any sense to create one static page for each game. Instead, you'll want to create a page template which is dynamically updated based on the user's request to learn more about a particular game. You can pass variables from the route function into your page like this:

F3::route('GET /game',
  function() {
    F3::set('title', 'Super Mario Brothers');
    F3::set('publisher', 'Nintendo');
    F3::set('year', '1985');
    echo F3::serve("pages/game.html");
  }
);

The game.html file must include placeholders for each variable. For instance, you could output each of the variables defined within the route function by adding the following text to game.html:

{@title} was created by {@publisher} in {@year}.

With both pieces in place, requesting /game to the browser will result in the following string being output to the browser:

Super Mario Brothers was created by Nintendo in 1985. 

Integrating a MySQL Database with PHP Fat-Free

In order to make the video game website fully dynamic you'll need to retrieve the data from your database. This is incredibly easy to do using Fat-Free. The following example uses a dynamic title slug passed via the route to query a MySQL database table. All of this should be quite straightforward except for the AUTOLOAD-related call. This call is responsible for identifying the location of the sqldb plugin which is packaged with the Fat-Free download. If you look inside this directory you'll find a list of 20 different plugins which you can use to enhance your website's capabilities.

<!--p

require_once 'F3/F3.php';


F3::route('GET /game/@slug',
  function() {

    F3::set('AUTOLOAD','/home/wjgilmore/Downloads/fatfree-1.4.4/autoload/');

    F3::set('DB',
      array(
        'dsn-->'mysql:host=localhost;port=3306;dbname=fat_games',
        'user'=>'root',
        'password'=>'jason'
      )
    );

    $slug = F3::scrub(F3::get('PARAMS["slug"]'));

    F3::sql("SELECT title, publisher, released FROM games WHERE slug='$slug'");

    echo F3::serve("pages/game.html");
  }
);

F3::run();

The game.html template is then modified to iterate over any records returned from the query, which in the case of this particular example is exactly one:

{@game.title} was created by {@game.publisher} in {@game.released}.

Conclusion

Fat-Free provides developers with an incredibly rich set of functionality while staying true to its goal of keeping a trim waistline. If you're looking for a no-nonsense solution to building dynamic websites fast, Fat-Free is well worth a look.

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.