Building RESTfull app with Fat-Free (f3) PHP micro framework and Redis key-value store

Published: Tue, 13 Jun 2017 by Rad

Introduction

This is the post aimed at beginners with PHP frameworks. This site is built on top of Fat-Free (f3) framework and we have had few questions about this framework. Fat-Free according their own words is 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 use micro-frameworks

Pro Few plus reasons to consider:

  • not that steep learning curve, you can master one in a day, even hours
  • flexible, mostly without rigid project structure - this may be prpblem for bigger projects
  • performance (see filtered benchmark of php framworks: Episode 10: The Performance Awakens )
  • do few things but they do it well

Against on the negative side:

  • smaller user base, less help in forums, not enough tutorials
  • documentation may be poor
  • some require advanced PHP knowledge to follow framework logic
  • number of developers smaller, security consideration
  • release cycle and maintenance, they can die any moment

In the past when framework become hipped term, few distinctive fully blown frameworks evolved in PHP. We tried Zend Framework, Symfony, CodeIgniter, CakePHP etc. However, we quickly came to realization that many of them force their own MVC, try to be one solution for everything and performance was not great.

Next, we looked at mini and micro frameworks. For small web application you need just few things, clean code, flexibility in your code structure. MVC is different thing for different people, and how do you implement it with stateless HTTP? Do you really need it?

Since then major frameworks evolved and enable decoupling (Zend2, Symfony2), so you can choose just libraries from framework to use in your project independently.

Why use Fat-Free framework

This one is personal preference. Framework only supports PHP 5.3+, but frankly if you are still using 5.3 you are behind the times (and possibly security issues). We recommend at least PHP 5.4 or 5.5. There are other micro frameworks to consider (Slim, Wave, Phalcon to name few) or you may need just few libraries (e.g. klein for routing), all depends on your project size and requirements.

"The philosophy behind the framework and its approach to software architecture is towards minimalism in structural components, avoiding application complexity and striking a balance between code elegance, application performance and programmer productivity."

fatfreeframework.com

For us major selling point was: performance and the fact that it does not get into your way.

F3 offers

  • gentle learning curve
  • gives you solid foundation, fast in ~65kb of code
  • a mature code base
  • no-nonsense approach to writing web applications.
  • multilingual i18n support
  • supports both SQL and NoSQL databases off-the-shelf
  • e.g (MySQL, MongoDB, redis, Qlite, flat file db - Jig)
  • database session management system
  • markdown to html converter
  • image processor
  • Fast and clean template engine - similar to Twig
  • SMTP over SSL/TLS and much more
  • could be extended via plugins
More reading:

Brief description of app we are buidling

We will build simple web application, which will display daily exchange rates for selected currencies. Users will be able to query additional currencies if they need to. We should present results via RESTful API in JSON (or XML) and also directly via html page. We will get data by utilizing call to 3rd party API, do some business logic on data, store results in Redis cache and display cached results to end user.

REST. We will create simple RESTfull app which will display exchange currency rates. Those rates will be cached in Redis datastore for some period. App will get data via API call to selected provider - we can swap providers if needed. App could also plot graph, chart for selected currencies historically during the day or selected period.

Business logic. Upon reading data from external API app will add selected % to exchange rate and display it to end user. This may vary between currencies baskets. Imagine, this is arbitrage business, you getting currencies from the source, get to it your margin, and sell it to 3rd party in smaller quantities as they would be able to buy from your source..

Charts: For historical data we might want to store data in MySQL etc.

Our API: We also want to serve our data via API - in JSON, XML or any other format.

Logging & Limits: Performance of Redis will be monitored - maybe via Datadog or by sending data to DataDog or any other collector. Also we want limit our calls to our source API and 3rd parties call to our API.

  • we need collect external API hits
  • collect response time from Redis in ms
  • possibly whole app response time

Authentication: We want to consider authentication via key, so only selected sources can access our app. This might be done later and in the beginning everybody can have one key - like testing key!

Good API consideration

Good code is modular and each module has an API. Useful modules tend to get reused. However, once module has users we can not change API at will. Functionality should be easy to explain, as small as possible but no smaller ;).

Characteristics of a Good API

  • easy to learn
  • easy to use, even without documentation
  • hard to misuse
  • easy to read and maintain code that uses it
  • sufficiently powerful to satisfy requirements
  • easy to extend
  • appropriate to audience

Project structure

The code in this example will be Object Oriented. We will not use fully blown MVC pattern. Todo: note why! Instead we will split our application into routing element + business logic (which includes Models) and view.

- index.php 
- views (#folder, holds files for view)
- static (#folder holding static assets, images, css and js files for frontend)
- app (#folder, business logics, OOP)
- cache (#folder - writeable by server, cached views or any cached files)

# optionally
- viewTwig (folder, alternatively holds Twig files)
- logs (#folder - writeable by server, optional logging )

Fat-Free installation and prerequisites

Prerequisites

  • Web server running PHP, e.g nginx + php-fpm
  • PHP at least 5.3, but we recommend at least 5.5
  • Redis installed and running on port 6379
  • optionally - MySQL and DataDog client

For this tutorial you will need to have web server configured, PHP, opcache for PHP running, Redis server and optionaly MInnoDBDB (or MySQL).

The easiest way to install nginx + php-fpm, Redis key-value store and required PHP extensions to follow this tutorial … tutorial to follow … , or grab VirtualBox image we prepared for you. It is complete image based on Centos 6.5. Enjoy!

Installation

There are 2 options here. These days most developers use project management tools - like Composer. Installing packages via Composer is convinient, but sometimes not all packages cooperate.

Install Composer

Installing Composer requires access to command line and working PHP installed - run this command inside project directory:


          do something

        curl -sS https://getcomposer.org/installer | php

Composer file: composer.json - define your packages

At the heart is json file, where you define packages you want to install. This should reside in project directory.


    {
        "require": {
            "bcosca/fatfree": "dev-master",
            "css-crush/css-crush": "2.2.*@dev"
        }
    }

This make sure that composer will install Fat-Free framework and css crush. Css crush is css preprocessor very similar to Stylus and we like to use it in our projects. It is however written in PHP so you do not need to run Ruby, Node.js or some other languages for css preprocessing.

If you do not need css preprocessor and css minification in your project then this is optional (in such a case remove "css-crush/css-crush": "2.2.*@dev" from your json file).

Then run composer in terminal in the folder where your project is in order to install all required modules.


        php composer.phar install

Web server setup

In order for framework to work correctly we need to route all requests to non existent files and directories to routing interceptor. In our case it will be index.php file in folder /demo/fat-free-redis. In that file we will process requests and route them to appropriate objects where all logic will be done and then sent to views.

You can find more information for various web servers including built in web server for PHP 5.4+ on Fat-Free framework home page: Resource: http://fatfreeframework.com/routing-engine#DynamicWebSites

nginx setup

We will be using nginx with php-fpm and our app will be sitting in subdirectory /demo/fat-free-redis


location /demo/fat-free-redis {
    try_files $uri $uri/ /demo/fat-free-redis/index.php?_url=$uri&a=$args;
    root /home/lucasoft.info/public_html;
}

Back to :   Blog articles list

PHP, frameworks, Redis - from around the web

  • Fat-Free f3 php framework - home page of the framework
  • Redis NoSQL key-value data store - is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Back to :   Blog articles list

Our previous blogs stories

Special offer for readers