1-click AWS Deployment 1-click Azure Deployment
- Overview
- Features
- Videos
Overview
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
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.
Controller
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
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
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.
Module
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.
Package
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.
Workflow
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.
employee.php
<?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
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>/<action>
Where,
- 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.
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 (1.8.0.1) - Installing fuel/fuel (1.8.0.1) 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 (1.8.0.4) Loading from cache - Installing fuel/auth (1.8.0.4) Loading from cache - Installing fuel/email (1.8.0.4) Loading from cache - Installing fuel/oil (1.8.0.4) Loading from cache - Installing fuel/orm (1.8.0.1) Loading from cache - Installing fuel/parser (1.8.0.4) Loading from cache - Installing fuel/docs (1.8.0.4) 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 −
Usage: 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 Description: The 'oil' command can be used in several ways to facilitate quick development, help with testing your application and for running Tasks. Environment: 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 Documentation: http://docs.fuelphp.com/packages/oil/intro.html
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.
Result
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 </Directory> </VirtualHost>
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.
127.0.0.1 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
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,
dump
The dump method returns multiple mixed values to the browser in a formatted structured way.
Debug::dump($var1, $var2);
backtrace()
backtrace shows the detailed information about the current execution of code. It shows the PHP file information, current line, and all its previous actions.
Debug::backtrace();
classes()
Returns a list of all classes.
Debug::classes();
interfaces()
Returns a list of all interface classes.
Debug::interfaces();
includes()
Returns a list of all included files currently loaded at the runtime.
Debug::includes();
functions()
Returns a list of all functions.
Debug::functions();
constants()
Returns a list of all constants.
Debug::constants();
extensions()
Returns a list of all extensions.
Debug::extensions();
headers()
Returns a list of all HTTP headers.
Debug::headers();
phpini()
Prints a list of the configuration settings read from php.ini file.
Debug::phpini();
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.
PHPUnit
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 −
<?php 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.
<?php /** * @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,
fuel/app/views/layout.php
<!DOCTYPE html> <html lang = "en"> <head> <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> <script src = "/assets/js/bootstrap.min.js"></script> </head> <body> <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> </button> <a class = "navbar-brand" href = "#">FuelPHP Sample</a> </div> <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> </ul> </div><!--/.nav-collapse --> </div> </nav> <div class = "container"> <div class = "starter-template" style = "padding: 50px 0 0 0;"> <?php echo $content; ?> </div> </div><!-- /.container --> </body> </html>
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.
fuel/app/classes/controller/book.php
<?php 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,
fuel/app/views/index.php
<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.
fuel/app/config/routes.php
<?php 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,
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,
CREATE TABLE book ( id INT PRIMARY KEY AUTO_INCREMENT, 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.
INSERT INTO book(title, author, price) VALUES( 'The C Programming Language', 'Dennie Ritchie', 25.00 ),( 'The C++ Programming Language', 'Bjarne Stroustrup', 80.00 ),( 'C Primer Plus (5th Edition)', 'Stephen Prata', 45.00 ),('Modern PHP', 'Josh Lockhart', 10.00),( 'Learning PHP, MySQL & JavaScript, 4th Edition', 'Robin Nixon', 30.00 )
Step 7 Configure database
Configure the database using database configuration file, db.php located at fuel/app/config.
fuel/app/config/db.php
<?php 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/”.
fuel/app/config/config.php
'always_load' => array ( 'packages' => array ( 'orm' ), ),
Step 9 Create a model
Create a book model in book.php located at “fuel/app/classes/model”. It is defined as follows −
fuel/app/classes/model/book.php
<?php 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 ( 'id', 'title' => array ( 'data_type' => 'varchar', 'label' => 'Book title', 'validation' => array ( 'required', 'min_length' => array(3), 'max_length' => array(80) ), 'form' => array ( 'type' => 'text' ), ), 'author' => array ( 'data_type' => 'varchar', 'label' => 'Book author', 'validation' => array ( 'required', ), 'form' => array ( 'type' => 'text' ), ), 'price' => array ( 'data_type' => 'decimal', 'label' => 'Book price', 'validation' => array ( 'required', ), '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.
fuel/app/classes/controller/book.php
<?php 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,
fuel/app/views/book/index.php
<table class = "table"> <thead> <tr> <th>#</th> <th>Title</th> <th>Author</th> <th>Price</th> <th></th> </tr> </thead> <tbody> <?php foreach($books as $book) { ?> <tr> <td><?php echo $book['id']; ?></td> <td><?php echo $book['title']; ?></td> <td><?php echo $book['author']; ?></td> <td><?php echo $book['price']; ?></td> <td> <a href = "/book/edit/<?php echo $book['id']; ?>">Edit</a> <a href = "/book/delete/<?php echo $book['id']; ?>">Delete</a> </td> </tr> <?php } ?> </tbody> </table> <ul> </ul>
Now, requesting the URL, http://localhost:8080/ will show the page as follows −
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'); $book->save(); Response::redirect('book'); } 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,
<style> #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; } </style> <div id = "form"> <h2>Book form</h2> <?php if(isset($errors)) { echo $errors; } echo $form; ?> </div>
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,
Form
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
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'); $fieldset->populate($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'); $book->save(); Response::redirect('book'); } 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
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 { $book->delete(); } Response::redirect('book'); }
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.