1-click AWS Deployment    1-click Azure Deployment


FuelPHP is an open source web application framework. It is written in PHP 5.3 and implements HMVC pattern. HMVC is Hierarchical Model-View-Controller framework that allows to sub-request the controller, which returns the partial page such as comments, menus, etc., instead of the complete page as in normal MVC.

FuelPHP is created with a desire to incorporate best practices from frameworks such as CodeIgniter and Kohana with improvements and ideas of its own. FuelPHP database migration tool and scaffolding functionalities are inspired by the popular Ruby on Rails framework.

  • FuelPHP leverages the power of command line through a utility called “Oil”. The utility is designed to help speed up development, increase efficiency, testing, debugging, and HTML support.
  • FuelPHP is purely an object-oriented approach. Its architecture is based on the idea of modularity. Applications can be divided into modules and every component can be extended or replaced without rewriting a single line of code. Fuel supports any template parser such as Smarty, Twig, PHPTal, etc. for parsing views.
  • FuelPHP community is large and active with over 300 contributors. Its large community regularly creates and improves packages and extensions. The main objective of FuelPHP framework is to provide flexibility and compatibility. It is fast, easy to learn, and a complete solution for developing web applications.
  • What makes FuelPHP one of the premier frameworks used by PHP developers is that – the new version of FuelPHP is reverse-compatible with its older versions because of its stable API. It is extremely flexible.
  • Packages and modules make it easy and simple to reuse an existing code in a systematic way. FuelPHP offers maximum performance through a small library. Its interactive debugging allows to easily eliminate the errors in development. Also, its clean and stable code makes programming easier.


FuelPHP – Architecture Overview

FuelPHP is based on battle tested Model-View-Controllerarchitecture along with HMVC (Hierarchical MVC) support. While MVC provides flexible and layered application development, HMVC goes one step further to enable widgetization of the web application.The strength of FuelPHP is that it does not enforce specific ways to develop an application. It just provides a simple and easy-to-use standard structure. Developers are free to use the pre-defined set of functionality provided by FuelPHP or modify it whenever needed. All the features provided by FuelPHP including the core feature can be changed according to the requirement of the application.


Model is the business entity of the application. Controller and View exchange data in the form of Model. Model enables uniform representation of our business data. It enables the database layer to interact with the web application layer in the standard way and provides an option to select, save, edit, and delete our database entities.


A typical MVC application starts from a Controller. Once a user sends a request to the FuelPHP web application, the application gathers all the information about the request and sends it to the Controller. Controller does the required business logic of the requested page and then calls the relevant View along with the processed data in the form of Models.


View is the presentation layer of the MVC application. View decides how to show the Model to the user. It supports simple data rendering to the advanced layout, which enables the website to normalize the design across all the pages. View also provides theming support, which enables quick design change across the application.


Presenter is a special feature provided by FuelPHP. It is the glue between Controller and View. Controller can share some of its low level responsibility such as retrieving model from database, generating data for the view, etc. Controller calls Presenter instead of View, which in turn calls View. Presenter enables pure separation of business logic and presentation layer.

Hierarchical MVC

FuelPHP provides an option to call one controller from another controller, similar to the request from the client (browser). If any controller calls another controller, the called controller will return the response to the calling controller instead of rendering it to the client (browser). This enables widgetization of the web application. For example, the comment section can be showed as a stand-alone page as well as a sub-section of the main (blog) page.


One of the salient features of FuelPHP is that a section of the web application can be converted into modules, which can be shared among the different application. For example, a blog module created for an application can be reused in another application by just copying the module code from source application to target application.Note that creating a new module is as simple as developing the main application. The structure is similar to the main application with the only exception that the module should be coding a separate folder.


FuelPHP provides an option to organize the code into a single unit called Package. A package can contain one or more functionality needed for the web application. For example, a database component such as ORM, email, etc., can be organized into a package and used whenever needed.A Package is different from a Module in the sense that the Package does not contain any web pages or partial web pages. Package can be used in FuelPHP as well as any other PHP framework.


The workflow of the FuelPHP is simple and easy to understand. It is depicted in the following diagram.

  • User sends a request to the application.
  • Controller receives the request and gathers information by interacting with the model, which in turn interacts with the database.
  • Controller gathers information by interacting with other controller by sending a subrequest to the other controllers.
  • Controller sends the retrieved model to the view, which in turn generates the presentation and sends it to the client as a response.
  • In some cases, the controller may pass the control to the presenter. In that case, the presenter gathers information from the model and sends it to the client. Here, the presenter does not perform any business logic, except retrieve the model from the database.

FuelPHP – Simple Web Application

In this chapter, we will see how to create a simple application in FuelPHP framework. As discussed earlier, you know how to create a new project in Fuel. We can take an example of Employee details.

Let’s start by creating a project named Employee using the following command.

oil create employee

After executing the command, an employee project is created with the following file structure −

employee ├── CHANGELOG.md ├── composer.json ├── composer.lock ├── composer.phar ├

Structure of the Application

FuelPHP framework provides a well-organized application structure. Let us check some of the important files and folders of the application.

  • fuel − Contains all the PHP files.
  • public − Contains all the assets which are directly accessed through the browser such as JavaScript, CSS, images, etc.
  • oil − An executable used to run command line tasks such as generating code or interactive debugging within your application. It’s optional.
  • fuel/app/ − Contains all application-specific PHP files. It contains Models, Views, and Controllers.
  • fuel/core/ − This is where Fuel framework itself lives.
  • fuel/packages/ − Contains all fuel packages. By default, fuel will contain three packages: oil, auth, and orm. These packages will not be loaded unless you require them.
  • fuel/app/config/ − Contains all application-related configuration files. The main application configuration file, config.php file is located here.
  • fuel/app/classes/ − Contains all the application specific MVC based PHP files. It contains controllers, models, helper classes, libraries, etc.
  • fuel/app/classes/controller/ − Controllers are placed here.
  • fuel/app/classes/model/ − Models are placed here.
  • fuel/app/views/ − Contains view files. There are no specific naming conventions for views.

Add a Controller

As discussed earlier, FuelPHP is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. In MVC pattern, the controller plays an important role and every webpage in an application needs to be handled by a controller. By default, controllers are located in fuel/app/classes/controller/ folder. You can create your own Controller class here.

Move to the location fuel/app/classes/controller/ and create employee.php file. To create a new controller, just extend the Controller class provided by FuelPHP, defined as follows.


<?php    class Controller_Employee extends Controller {       public function action_home() {                   // functionality of the home page           echo "FuelPHP-Employee application!";       }    }

Now, we have created an Employee Controller and added a public method, action_home, which prints a simple text.


Routing resolves the web page URI into specific controller and action. Every webpage in a FuelPHP application should go through routing before the actual execution of the controller. By default, each controller can be resolved using the following URI pattern.



  • controller is the name of the controller minus namespace, employee
  • action is the name of the method minus action_ keyword, home

The newly created controller can be accessed by http://localhost:8080/employee/home and it will produce the following result.


FuelPHP – Installation

System Requirements

Before moving to installation, the following system requirements have to be satisfied.

Web server (Any of the following)

  • WAMP (Windows)
  • Microsoft IIS (Windows)
  • LAMP (Linux)
  • MAMP (Macintosh)
  • XAMP (Multi-platform)
  • Nginx (Multi-platform)
  • PHP in-built development web server (Multi-platform)

Browser support (Any of the following)

  • IE (Internet Explorer 8+)
  • Firefox
  • Google Chrome
  • Safari

PHP compatibility − PHP 5.3 or later. To get the maximum benefit, use the latest version.

Let us use PHP’s in-built development web server for this tutorial. The built-in development web server is easy to start as well as quite adequate to understand the basics of FuelPHP web application without getting into the complexity of the world of web server and configurations.

Command Line Installation

The command line installation of FuelPHP is very easy and takes maximum of five minutes.

Install Oil Package

Oil is a special package/command provided by FuelPHP framework to do lot of tasks needed in the development of FuelPHP application including installation, development, and testing the application.

To install the Oil package, open up a shell and run the following command −

sudo curl https://get.fuelphp.com/oil | sh

The command uses curl to download and install the oil package. The command will show result similar to the following information and finally install the oil package.

 % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current 
                                 Dload  Upload   Total   Spent    Left  Speed 
100   479  100   479    0     0    353      0  0:00:01  0:00:01 --:--:--   353

Create a New Project

To create a new project using Oil, use the following command −

oil create <project_name>

Let’s create a new project named “HelloWorld” using the following command.

oil create HelloWorld

Now, you can see response similar to the following and finally create a simple skeleton FuelPHP application.

composer create-project fuel/fuel HelloWorld 
Installing fuel/fuel ( 
   - Installing fuel/fuel ( 
      Loading from cache  

Created project in HelloWorld  

Loading composer repositories with package information 
Updating dependencies (including require-dev) 
   - Installing composer/installers (v1.3.0) 
      Loading from cache
   - Installing fuelphp/upload (2.0.6) 
      Loading from cache  
   - Installing michelf/php-markdown (1.4.0) 
      Loading from cache  
   - Installing psr/log (1.0.2) 
      Loading from cache  
   - Installing monolog/monolog (1.18.2) 
      Loading from cache  
   - Installing phpseclib/phpseclib (2.0.0) 
      Loading from cache  
   - Installing fuel/core ( 
      Loading from cache  
   - Installing fuel/auth ( 
      Loading from cache  
   - Installing fuel/email ( 
      Loading from cache  
   - Installing fuel/oil ( 
      Loading from cache  
   - Installing fuel/orm ( 
      Loading from cache  
   - Installing fuel/parser ( 
      Loading from cache  
   - Installing fuel/docs ( 
      Loading from cache
   Writing lock file
   Generating autoload files 

Oil Version

To test whether Oil is available and to check the version, use the following command −

$ cd HelloWorld
$ php oil -v

The above command produces the following result −

Fuel: 1.8 running in "development" mode

Oil Help Command

To obtain Oil’s basic help documentation, use the following command −

$ php oil help

The above command will show the help documentation similar to the following result −

   php oil [cell|console|generate|package|refine|help|server|test]  
Runtime options: 
   -f, [--force]    # Overwrite files that already exist 
   -s, [--skip]     # Skip files that already exist 
   -q, [--quiet]    # Supress status output 
   -t, [--speak]    # Speak errors in a robot voice  
   The 'oil' command can be used in several ways to facilitate quick development, help 
   with testing your application and for running Tasks.  
   If you want to specify a specific environment oil has to run in, overload the 
   environment variable on the commandline: FUEL_ENV=staging php oil <commands>
More information: 
   You can pass the parameter "help" to each of the defined command to get 
   information about that specific command: php oil package help  

As of now, you have an idea of how to install Fuel using Oil. Let’s go through the composer based installation in the next section.

Composer-based Installation

The following command is used to install FuelPHP using Composer.

$ composer create-project fuel/fuel --prefer-dist.

Git Repository Clones

To install the latest development version as local git repository clones, use the following command.

$ composer create-project fuel/fuel:dev-1.9/develop --prefer-source.

Running the Application

Move to the project directory public folder, run the application using the production server with the following command.

$ cd path/to/HelloWorld/public
$ php -S localhost:8080 index.php

It produces the following response.

PHP 5.5.31 Development Server started at Sun May 21 12:26:10 2017
Listening on http://localhost:8080
Document root is /Users/workspace/php-fuel/HelloWorld/public
Press Ctrl-C to quit.

Now, request the URL, http://localhost:8080 and it will produce the following result.


Welcome Page

This is the simplest way to run FuelPHP application in the development environment. If you create your application in this way in the production environment, you will face security issues. The recommended way is setting up a virtual host configuration. It is explained for apache web server in the next section.

Setting Up a Virtual Host

It is more secure way to access FuelPHP application. To set up a virtual host, you need to link apache virtual host file to your application. In case of intranet application, redirect system host file URL to virtual host.

Virtual Host File

Open the virtual host and add the following changes.

<VirtualHost *:80> 
   ServerName hello.app 
   DocumentRoot /path/to/public 
   SetEnv FUEL_ENV “development”
   <Directory /path/to/public> 
      DirectoryIndex index.php 
      AllowOverride All 
      Order allow,deny 
      Allow from all 

System Host File

Now, add a host entry to your machine using the following command.

sudo vi /etc/hosts

Then, add the following line to the end of the file. hello.app

To make all the changes available, restart your Apache server and request the url, http://hello.app. It produces the FuelPHP home page.

FuelPHP – Error Handling & Debugging

FuelPHP provides an excellent support for handling the errors and debugging the application. Let us understand error handling and debugging in this chapter.

Error Handling

FuelPHP error handling is based on exceptions. FuelPHP provides PhpErrorException exception for all old php errors. FuelPHP raises PhpErrorException whenever an error in the PHP code is encountered. FuelPHP also makes it easy to display custom error pages for various HTTP status codes.

File Not Found Error

FuelPHP provides a new exception class, HttpNotFoundException to handle the unknown requests. Sometimes, we may encounter the request which may not be handled. At that time, we can just throw the HttpNotFoundException.

By default, a default page is configured for HttpNotFoundException in the routes configuration file, fuel/app/config/routes.php using 400 entry. Whenever HttpNotFoundException is raised, the request will get redirected to 400 page.

'_404_'   => 'welcome/404',    // The main 404 route 

Internal Errors

FuelPHP provides a new exception class, HttpServerErrorException to handle all server errors. Sometimes, we may not be able to process the given request due to internal errors. At that time, we can just throw the HttpServerErrorException.

By default, a default page is configured for HttpServerErrorException in the routes configuration file, fuel/app/config/routes.php using 500 entry. Whenever HttpServerErrorException is raised, the request will get redirected to 500 page.

'_500_'   => 'welcome/500',    // The main 500 route

This page will log the error, show the will formatted error in the page and occasionally send a notification to the system administrator.

Access Violation Errors

FuelPHP provides a new exception class, HttpNoAccessException to handle the access violations. Sometimes, we may not be able to process the request due to access restriction. At that time, we can just throw the HttpNoAccessException.

By default, a default page is configured for HttpNoAccessException in the routes configuration file, fuel/app/config/routes.php using 403 entry. Whenever HttpNoAccessException is raised, the request will get redirected to 403 page.

'_403_'   => 'welcome/403',     // The main 403 route 

This page will show the access violation information.


Debugging is one of the most frequent activities developing an application. FuelPHP provides a simple class, Debug to handle the debugging activity of the application. Let us learn the Debug class and its methods in this chapter.

Debug Class

Debug class provides utility methods to show the detailed information of variables, objects, array, etc. Debug class provides the following methods,


The dump method returns multiple mixed values to the browser in a formatted structured way.

Debug::dump($var1, $var2);


backtrace shows the detailed information about the current execution of code. It shows the PHP file information, current line, and all its previous actions.



Returns a list of all classes.



Returns a list of all interface classes.



Returns a list of all included files currently loaded at the runtime.



Returns a list of all functions.



Returns a list of all constants.



Returns a list of all extensions.



Returns a list of all HTTP headers.



Prints a list of the configuration settings read from php.ini file.


FuelPHP – Unit Testing

Unit testing is an essential process in developing large projects. Unit tests help to automate the testing of the application’s components at every stage of development. It alerts when the component of the application is not working according to the business specification of the project. Unit testing can be done manually but is often automated.


FuelPHP framework integrates with the PHPUnit testing framework. To write a unit test for the FuelPHP framework, we need to set up the PHPUnit. If PHPUnit is not installed, then download and install it. We can confirm the availability of PHPUnit in our system using the following command.

phpunit --version

If PHPUnit is available, you will see the result similar to the following.

PHPUnit 5.1.3 by Sebastian Bergmann and contributors. 

Creating Unit Tests

The standard location provided by FuelPHP to write unit test is fuel/app/tests. We can write the unit test for controller, model, view and presenters in separate folders. Let us write a unit test to validate the Model_Employee object.

  • Step 1 − Create a folder, model under fuel/app/tests folder.
  • Step 2 − Create a file, employee.php under fuel/app/tests/model/ folder.
  • Step 3 − Create a new test class, Test_Model_Employee by extending TestCase class provided of PHPUnit.
  • Step 4 − Write a method, testInstanceOfEmployee() to asset the employee object creation using assertInstanceOf() method provided by PHPUnit’s TestCase class.

Following is the complete code −

   class Test_Model_Employee extends TestCase { 
      public function testInstanceOfEmployee() { 
         $this->assertInstanceOf(Model_Employee::class, new Model_Employee()); 

Creating a Test Group

FuelPHP provides an option to create a group of test cases. Creating a group is as simple as adding docblock attribute, @group. Let us include our test case inside the MyTest group.

      * @group MyTest 
   class Test_Model_Employee extends TestCase { 
      public function testInstanceOfEmployee() { 
         $this->assertInstanceOf(Model_Employee::class, new Model_Employee()); 

Run Test

To run all the test in the directory, use the following command.

$ php oil test

To run a specific group of tests, use the following command.

$ php oil test --group = MyTest

After executing the command, you will receive the following response.

Tests Running...This may take a few moments.
PHPUnit 5.1.3 by Sebastian Bergmann and contributors.
                                        1 / 1 (100%).
Time: 123 ms, Memory: 8.00Mb
OK (1 test, 1 assertion)

FuelPHP – Complete Working Example

Step 1 Create a project

Create a new project named “BookStore” in FuelPHP using the following command.

oil create bookstore

Step 2 Create a layout

Create a new layout for our application. Create a file, layout.php at location fuel/app/views/layout.php. The code is as follows,


<!DOCTYPE html> 
<html lang = "en"> 
      <meta charset = "utf-8"> 
      <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> 
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">  
      <title><?php echo $title; ?></title>  
      <!-- Bootstrap core CSS --> 
      <link href = "/assets/css/bootstrap.min.css" rel = "stylesheet">  
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      <script src = "/assets/js/bootstrap.min.js"></script> 
      <nav class = "navbar navbar-inverse navbar-fixed-top"> 
         <div class = "container"> 
            <div class = "navbar-header">
               <button type = "button" class = "navbar-toggle collapsed" 
                  datatoggle = "collapse" data-target = "#navbar" 
                  aria-expanded = "false" ariacontrols = "navbar"> 
                  <span class=  "sr-only">Toggle navigation</span> 
                  <span class = "icon-bar"></span> 
                  <span class = "icon-bar"></span> 
                  <span class = "icon-bar"></span> 
               <a class = "navbar-brand" href = "#">FuelPHP Sample</a> 
            <div id = "navbar" class = "collapse navbar-collapse"> 
               <ul class = "nav navbar-nav"> 
                  <li class = "active"><a href = "/book/index">Home</a></li> 
                  <li><a href = "/book/add">Add book</a></li> 
            </div><!--/.nav-collapse --> 
      <div class = "container"> 
         <div class = "starter-template" style = "padding: 50px 0 0 0;"> 
            <?php echo $content; ?> 
      </div><!-- /.container --> 

Here, we are using bootstrap template. FuelPHP has first class support for bootstrap templates. We have created two variables, title and content. title is used to specify the current page’s title and content is used to specify the current page details.

Step 3 Create a Controller

Create a new controller, Controller_Book to show, add, edit, and delete the book. Create a new file, fuel/app/classes/controller/book.php and place the following code.


   class Controller_Book extends Controller_Template {
      public $template = 'layout'; 
      public function action_index() { 
         // Create the view object 
         $view = View::forge('book/index');  
         // set the template variables 
         $this->template->title = "Book index page"; 
         $this->template->content = $view; 

Here, we have created the book controller by inheriting template controller and set the default template as fuel/app/views/layout.php.

Step 4 Create the index view

Create a folder, book in views directory under fuel/app/views folder. Then, create a file index.php inside the book folder and add the following code,


<h3>index page</h3>

As of now, we have created a basic book controller.

Step 5 Modify the default route

Update the default route to set the home page of the application to book controller. Open the default routing configuration file, fuel/app/config/routes.php and change it as follows.


   return array ( 
      '_root_'  => 'book/index',  // The default route 
      '_404_'   => 'welcome/404', // The main 404 route 

      'hello(/:name)?' => array('welcome/hello', 'name' => 'hello'), 

Now, requesting the URL, http://localhost:8080/ will return the index page of the book controller as follows,

Return Index Page

Step 6 Create database

Create a new database in MySQL server, using the following command,

create database tutorialspoint_bookdb 

Then, create a table inside the database using the following command,

   title VARCHAR(80) NOT NULL, 
   author VARCHAR(80) NOT NULL, 
   price DECIMAL(10, 2) NOT NULL 

Insert some sample record into the table using the following SQL statement.

   'The C Programming Language', 
   'Dennie Ritchie', 
   'The C++ Programming Language', 
   'Bjarne Stroustrup', 
   'C Primer Plus (5th Edition)', 
   'Stephen Prata', 
),('Modern PHP', 'Josh Lockhart', 10.00),( 
   'Learning PHP, MySQL & JavaScript, 4th Edition', 
   'Robin Nixon', 

Step 7 Configure database

Configure the database using database configuration file, db.php located at fuel/app/config.


   return array ( 
      'development' => array ( 
         'type'           => 'mysqli', 
         'connection'     => array ( 
            'hostname'       => 'localhost', 
            'port'           => '3306', 
            'database'       => 'tutorialspoint_bookdb', 
            'username'       => 'root', 
            'password'       => 'password', 
            'persistent'     => false, 
            'compress'       => false, 
         'identifier'     => '`', 
         'table_prefix'   => '', 
         'charset'        => 'utf8', 
         'enable_cache'   => true, 
         'profiling'      => false, 
         'readonly'       => false, 
      'production' => array ( 
         'type'           => 'mysqli', 
         'connection'     => array ( 
            'hostname'       => 'localhost', 
            'port'           => '3306', 
            'database'       => 'tutorialspoint_bookdb', 
            'username'       => 'root', 
            'password'       => 'password', 
            'persistent'     => false, 
            'compress'       => false, 
         'identifier'     => '`', 
         'table_prefix'   => '', 
         'charset'        => 'utf8', 
         'enable_cache'   => true, 
         'profiling'      => false, 
         'readonly'       => false, 

Step 8 Include Orm package

Update the main configuration file to include ORM package. It is located at “fuel/app/config/”.


'always_load' => array ( 
   'packages' => array ( 

Step 9 Create a model

Create a book model in book.php located at “fuel/app/classes/model”. It is defined as follows −


   class Model_Book extends Orm\Model { 
      protected static $_connection = 'production'; 
      protected static $_table_name = 'book'; 
      protected static $_primary_key = array('id'); 
      protected static $_properties = array ( 
         'title' => array ( 
            'data_type' => 'varchar', 
            'label' => 'Book title', 
            'validation' => array ( 
               'min_length' => array(3),  
               'max_length' => array(80) 
            'form' => array ( 
               'type' => 'text' 
         'author' => array ( 
            'data_type' => 'varchar', 
            'label' => 'Book author', 
            'validation' => array ( 
            'form' => array ( 
               'type' => 'text' 
         'price' => array ( 
            'data_type' => 'decimal', 
            'label' => 'Book price', 
            'validation' => array ( 
            'form' => array ( 
               'type' => 'text' 
      protected static $_observers = array('Orm\\Observer_Validation' => array ( 
         'events' => array('before_save') 

Here, we have specified the database details as properties of the model. It has validation details as well.

Step 10 Display books

Update the index action in book controller to list the available books in the database.


   class Controller_Book extends Controller_Template { 
      public $template = 'layout'; 
      public function action_index() { 
         // Create the view object 
         $view = View::forge('book/index');  
         // fetch the book from database and set it to the view 
         $books = Model_Book::find('all'); 
         $view->set('books', $books);  
         // set the template variables
         $this->template->title = "Book index page"; 
         $this->template->content = $view; 

Here, we have used the orm to fetch the book details from the database and then passed the book details to views.

Step 11 Update index view

Update the view file index.php located at “fuel/app/views/book”. The complete updated code is as follows,


<table class = "table"> 
         foreach($books as $book) {  
         <td><?php echo $book['id']; ?></td> 
         <td><?php echo $book['title']; ?></td> 
         <td><?php echo $book['author']; ?></td> 
         <td><?php echo $book['price']; ?></td> 
            <a href = "/book/edit/<?php echo $book['id']; ?>">Edit</a> 
            <a href = "/book/delete/<?php echo $book['id']; ?>">Delete</a> 

Now, requesting the URL, http://localhost:8080/ will show the page as follows −

Index View

Step 12 Create action to add book

Create the functionality to add a new book into the bookstore. Create a new action, action_add in the book controller as follows,

public function action_add() { 
   // create a new fieldset and add book model 
   $fieldset = Fieldset::forge('book')->add_model('Model_Book');  
   // get form from fieldset 
   $form = $fieldset->form();  
   // add submit button to the form 
   $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit'));
   // build the form  and set the current page as action  
   $formHtml = $fieldset->build(Uri::create('book/add'));  
   $view = View::forge('book/add'); 
   $view->set('form', $formHtml, false);  
   if (Input::param() != array()) { 
      try { 
         $book = Model_Book::forge(); 
         $book->title = Input::param('title'); 
         $book->author = Input::param('author'); 
         $book->price = Input::param('price'); 
      } catch (Orm\ValidationFailed $e) { 
         $view->set('errors', $e->getMessage(), false); 
   $this->template->title = "Book add page";  
   $this->template->content = $view; }

Here the following two processes are being performed,

  • Building the book form to add book using Fieldset methods and Book model.
  • Processing the book form, when the user enters the book information and submitted back the form. It can be found by checking the Input::param() method for any submitted data. Processing the form involves the following steps −
    • Gather the book information.
    • Validate the book information. We have already set the validation to be called before save method. If the validation fails, it will throw Orm\ValidationFailed exception.
    • Store the book information into the database.
    • Redirect the user to index page on success. Otherwise, show the form again.

We are doing both, showing the form as well as processing the form in the same action. When the user calls the action for the first time, it will show the form. When the user enters the book information and submits the data, then it will process the form.

Step 13 Create the view for add book action

Create the view for add book action. Create a new file, fuel/app/views/book/add.php and enter the following code,

   #form table { 
      width: 90%; 
   #form table tr { 
      width: 90% 
   #form table tr td { 
      width: 50% 
   #form input[type = text], select { 
      width: 100%; 
      padding: 12px 20px; 
      margin: 8px 0; 
      display: inline-block; 
      border: 1px solid #ccc; 
      border-radius: 4px; 
      box-sizing: border-box; 
   #form input[type = submit] { 
      width: 100%;
      background-color: #3c3c3c; 
      color: white; 
      padding: 14px 20px; 
      margin: 8px 0; 
      border: none; 
      border-radius: 4px; 
      cursor: pointer; 
   #form div { 
      border-radius: 5px; 
      background-color: #f2f2f2; 
      padding: 20px; 

<div id = "form">  
   <h2>Book form</h2> 
      if(isset($errors)) { 
         echo $errors; 
      echo $form;  

Here, we are just showing the form created in the action method. In addition, we are showing the errors, if any.

Step 14 Checking the add book action

Requesting the url, http://localhost:8080/book/add or clicking the Add book navigation link, will show the form as follows,


Updated View

Form with data

Form With Data

After entering the book information and submitting the page, the book information will be stored into the database and the page gets redirected to index page as follows.

Book list with newly added book

Book List

Step 15 Creating action to edit book

Create the functionality to edit and update the existing book information. Create a new action, action_edit in the book controller as follows.

public function action_edit($id = false) { 
   if(!($book = Model_Book::find($id))) { 
      throw new HttpNotFoundException(); 
   // create a new fieldset and add book model 
   $fieldset = Fieldset::forge('book')->add_model('Model_Book'); 
   // get form from fieldset 
   $form = $fieldset->form();  
   // add submit button to the form
   $form->add('Submit', '', array('type' => 'submit', 'value' => 'Submit'));  
   // build the form  and set the current page as action  
   $formHtml = $fieldset->build(Uri::create('book/edit/' . $id));  
   $view = View::forge('book/add'); 
   $view->set('form', $formHtml, false);  
   if (Input::param() != array()) { 
      try { 
         $book->title = Input::param('title'); 
         $book->author = Input::param('author'); 
         $book->price = Input::param('price'); 
      } catch (Orm\ValidationFailed $e) { 
         $view->set('errors', $e->getMessage(), false); 
   $this->template->title = "Book edit page"; 
   $this->template->content = $view; 

It is similar to add action, except it searches the requested book by id before processing the page. If any book information is found in the database, it will proceed and show the book information in the form. Otherwise, it will throw file not found exception and exit.

Step 16 Create the view for edit action

Create the view for edit book action. Here, we are using the same view used for add action.

Step 17 Checking the edit book action.

Click the edit link of any book in the book listing page, it will show the corresponding book form as follows −

Form with book details

Form Book Details

Step 18 Create action to delete book

Create the functionality to delete book from the bookstore. Create a new action, action_delete in the book controller as follows,

public function action_delete($id = null) { 
   if ( ! ($book = Model_Book::find($id))) { 
      throw new HttpNotFoundException(); 

   } else { 

Here, we are checking for the existence of book in the database using the supplied book id. If the book is found, then it is deleted and redirected to index page. Otherwise, a page not found information will be shown.

Step 19 Checking the delete action

Check the delete action by clicking the delete link in the book listing page. It will delete the requested book and then again be redirected to the index page.

Finally, all the functionalities to add, edit, delete, and list the book information is created.

FuelPHP is simple, flexible, scalable, and easily configurable compared to other MVC based PHP frameworks. It provides all the features of the modern MVC framework. It can be used as is or can be changed completely to suit our needs. Above all, it is a great choice for web development

FuelPHP – Advantages

FuelPHP is an elegant HMVC PHP 5.3 framework that provides a set of components for building web applications with the following advantages −

  • Modular structure − Fuel doesn’t force you to use modules or an HMVC file structure. If you want to use, the process is quite easy to integrate. FuelPHP apps are created in a modular structure and becomes easier for developers with clear benefits.
  • HMVC pattern − The most important feature of this framework is HMVC (Hierarchical Model View Controller) which makes it easy to access or use any properties, class methods, functions, files at higher level.
  • Secure hashing function − FuelPHP supports strong cryptography tools and password hashing techniques. It handles encryption, decryption, and hashing using the powerful PHPSecLib.
  • Scaffolding functionality − Scaffolding is a meta-programming method for building database operations. Fuel’s scaffolding is pretty easy. It allows you to get a basic CRUD application with very simple steps.

The following popular products use FuelPHP Framework −

  • Matic Technology − Global provider of offshore custom software development solutions. At Matic Technologies, they provide all the best possible solutions through FuelPHP according to the requirements of the client.
  • Kroobe − Kroobe is a social networking classifieds company. Fuel offers extremely low development costs and services to Kroobe team to achieve efficient solution.

-FuelPHP is a simple, flexible, community driven PHP 5.3+ framework, based on the best ideas of other frameworks, with a fresh start!FuelPHP is a MVC (Model-View-Controller) framework that was designed from the ground up to have full support for HMVC as part of its architecture. FuelPHP is extremely portable, works on almost any server and prides itself on clean syntax.FuelPHP is released under the The MIT License.



Features of FuelPHP

Using a Bespoke PHP or a custom-developed framework could give you a greater performance. FuelPHP provides many features, documentation, and a great community. The following sections describe some of the most useful features.


Although FuelPHP is a Model-View-Controller (MVC) framework, it was built to support the HMVC variant of MVC. Hierarchical Model-View-Controller (HMVC) is a way of separating logic and then reusing the controller logic in multiple places. This means that when a web page is generated using a theme or a template section, it can be split into multiple sections or widgets. Using this approach, it is possible to reuse components or functionality throughout a project or in multiple projects.In addition to the usual MVC structure, FuelPHP allows the use of presentation modules (ViewModels). These are a powerful layer that sits between the controller and the views, allowing for a smaller controller while still separating the view logic from both the controller and the views. If this isn’t enough, FuelPHP also supports a router-based approach where you can directly route to a closure. This then deals with the execution of the input URI.

Modular and extendable

The core of FuelPHP has been designed so that it can be extended without the need for changing any code in the core. It introduces the notion of packages, which are self-contained functionality that can be shared between projects and people. Like the core, in the new versions of FuelPHP, these can be installed via the Composer tool . Just like packages, functionality can also be divided into modules. For example, a full user-authentication module can be created to handle user actions, such as registration. Modules can include both logic and views, and they can be shared between projects. The main difference between packages and modules is that packages can be extensions of the core functionality and they are not routable, while modules are routable.


Everyone wants their applications to be as secure as possible; to this end, FuelPHP handles some of the basics for you. Views in FuelPHP will encode all the output to ensure that it’s secure and is capable of avoiding Cross-site scripting (XSS) attacks. This behavior can be overridden or can be cleaned by the included htmLawed library.The framework also supports Cross-site request forgery (CSRF) prevention with tokens, input filtering, and the query builder, which tries to help in preventing SQL injection attacks. PHPSecLib is used to offer some of the security features in the framework.

Oil – the power of the command line

If you are familiar with CakePHP or the Zend framework or Ruby on Rails, then you will be comfortable with FuelPHP Oil. It is the command-line utility at the heart of FuelPHP—designed to speed up development and efficiency. It also helps with testing and debugging. Although not essential, it proves indispensable during development.Oil provides a quick way for code generation, scaffolding, running database migrations, debugging, and cron-like tasks for background operations. It can also be used for custom tasks and background processes.


FuelPHP also comes with an Object Relation Mapper (ORM) package that helps in working with various databases through an object-oriented approach. It is relatively lightweight and is not supposed to replace the more complex ORMs such as Doctrine or Propel.

The ORM also supports data relations such as:

  • belongs-to
  • has-one
  • has-many
  • many-to-many relationships

Another nice feature is cascading deletions; in this case, the ORM will delete all the data associated with a single entry.The ORM package is available separately from FuelPHP and is hosted on GitHub

Base controller classes and model classes

FuelPHP includes several classes to give a head start on projects. These include controllers that help with templates, one for constructing RESTful APIs, and another that combines both templates and RESTful APIs.On the model side, base classes include CRUD (Create, Read, Update, and Delete) operations. There is a model for soft deletion of records, one for nested sets, and lastly a temporal model. This is an easy way of keeping revisions of data.

The authentication package

The authentication framework gives a good basis for user authentication and login functionality. It can be extended using drivers for new authentication methods. Some of the basics such as groups, basic ACL functions, and password hashing can be handled directly in the authentication framework.Although the authentication package is included when installing FuelPHP, it can be upgraded separately to the rest of the application. .

Template parsers

The parser package makes it even easier to separate logic from views instead of embedding basic PHP into the views. FuelPHP supports many template languages, such as Twig, Markdown, Smarty, and HTML Abstraction Markup Language (Haml).


Although not particularly a feature of the actual framework, the documentation for FuelPHP is one of the best available. It is kept up-to-date for each release .

What to look forward to in Version 2.0

Although this book focuses on FuelPHP 1.6 and newer, it is worth looking forward to the next major release of the framework. It brings significant improvements but also makes some changes to the way the framework functions.

Global scope and moving to dependency injection

One of the nice features of FuelPHP is the global scope that allows easy static syntax and instances when needed. One of the biggest changes in Version 2 is the move away from static syntax and instances. The framework used the Multiton design pattern, rather than the Singleton design pattern. Now, the majority of Multitons will be replaced with the Dependency Injection Container (DiC) design pattern , but this depends on the class in question.

The reason for the changes is to allow the unit testing of core files and to dynamically swap and/or extend our other classes depending upon the needs of the application. The move to dependency injection will allow all the core functionality to be tested in isolation.Before detailing the next feature, let’s run through the design patterns in more detail.


Ensures that a class only has a single instance and it provides a global point of access to it. The thinking is that a single instance of a class or object can be more efficient, but it can add unnecessary restrictions to classes that may be better served using a different design pattern.


This is similar to the singleton pattern but expands upon it to include a way of managing a map of named instances as key-value pairs. So instead of having a single instance of a class or object, this design pattern ensures that there is a single instance for each key-value pair. Often the multiton is known as a registry of singletons.

Dependency injection container

This design pattern aims to remove hard coded dependencies and make is possible to change them either at run time or compile time.One example is ensure that variables have default values but also allow for them to be overridden, also allow for other objects to be passed to class for manipulation.It allows for mock objects to be used whilst testing functionality.

Coding standards

One of the far-reaching changes will be the difference in coding standards. FuelPHP Version 2.0 will now conform to both PSR-0 and PSR-1. This allows a more standard auto-loading mechanism and the ability to use Composer. Although Composer compatibility was introduced in Version 1.5, this move to PSR is for better consistency. It means that the method names will follow the “camelCase” method rather than the current “snake_case” method names. Although a simple change, this is likely to have a large effect on existing projects and APIs.With a similar move of other PHP frameworks to a more standardized coding standard, there will be more opportunities to re-use functionality from other frameworks.

Package management and modularization

Package management for other languages such as Ruby and Ruby on Rails has made sharing pieces of code and functionality easy and common-place. The PHP world is much larger and this same sharing of functionality is not as common. PHP Extension and Application Repository (PEAR) was a precursor of most package managers. It is a framework and distribution system for re-usable PHP components. Although infinitely useful, it is not as widely supported by the more popular PHP frameworks.This deals with not only single packages, but also their dependencies. It allows projects to consistently set up with known versions of libraries required by each project. This helps not only with development, but also its testability of the project as well as its maintainability.It also protests against API changes. The core of FuelPHP and other modules will be installed via Composer and there will be a gradual migration of some Version 1 packages.

Backwards compatibility

A legacy package will be released for FuelPHP that will provide aliases for the changed function names as part of the change in the coding standards. It will also allow the current use of static function calling to continue working, while allowing for a better ability to unit test the core functionality.

Speed boosts

Although initially slower during the initial alpha phases, Version 2.0 is shaping up to be faster than Version 1.0. Currently, the beta version (at the time of writing) is 7 percent faster while requiring 8 percent less memory. This might not sound much, but it can equate to a large saving if running a large website over multiple servers. These figures may get better in the final release of Version 2.0 after the remaining optimizations are complete.

-Major Features Of  FuelPHP 

An (H)MVC framework

FuelPHP is a MVC (Model-View-Controller) framework that was designed from the ground up to have full support for HMVC as part of its architecture. But we didn’t stop there, we also added ViewModels (also known as presentation models) into the mix which give you the option to add a powerfull layer between the Controller and the View. FuelPHP also supports a more router based approach where you might route directly to a closure which deals with the input uri, making the closure the controller and giving it control of further execution.

  • Full HMVC implementation
  • ViewModels to get the View-specific logic out of your Views and Controllers
  • Route directly to closures

Modular and extendable to a fault

Almost every class in FuelPHP’s core package can be extended without you having to change a single line of code where it’s used on extending the core). You can package more functionality into packages that extend or replace the FuelPHP core and you can keep your application modular by dividing it up into application modules. Packages and modules are also a great way to enable re-use of your code.

  • Extend or replace Core classes without rewriting a single line of code.
  • Package additional functionality into Packages.
  • Create modular application by dividing it up into Application Modules.


Security concerns have been front and center from the beginning. Out-of-the-box FuelPHP’s Views will encode all your output to make it secure and prevent XSS attacks. If you need to allow HTML through you can mark it as safe or have it cleaned by the default included HTMLawed. FuelPHP also supports CSRF prevention with tokens, input filtering and the Query Builder will assist you in preventing any SQL injection attacks. Several security features inside the framework use functionality offered by PHPSecLib. More about Security in FuelPHP can be read in the documentation.

  • Input filtering
  • URI filtering
  • XSS filtering
  • Output encoding
  • CSRF token protection
  • SQL injection prevention

Oil: the power of the command line

FuelPHP leverages the power of the command line through a utility called “oil”. The utility is designed to help speed up development, increase efficiency and assist testing and debugging while being entirely optional if you are not a fan of the terminal.

  • Code generation, Scaffolding and Admin generation.
  • Run Database Migrations.
  • Interactive Debugging.
  • Tasks – useful for cron type activities like importing data and other batch or background operations.

Base classes for Controllers and Models

FuelPHP includes some base classes to give you a flying start.

  • Controller_Template – Add simple page templating functionality to your controllers.
  • Controller_Rest – An easy way to create a RESTful API.
  • Controller_Hybrid – Combine the two features into a single controller.
  • Model_Crud – Provides all methods for CRUD operations on a single table.



FuelPHP – Download, Install and Create



Related Posts