As a PHP developer, I have been a consistent user of different PHP frameworks, mostly focusing on CakePHP. Recently, I felt the need to go framework shopping and I have many valid reasons for choosing FuelPHP. It has a built-in modular structure and complete flexibility with emphasis on community. Before Fuel, I was a CakePHP user and just like Cake, Fuel is a huge community driven framework.
Key Takeaways
- FuelPHP is a flexible, full-stack PHP framework with a built-in modular structure and emphasis on community. It stands out for its HMVC (Hierarchical Model-View-Controller) architecture, router-based approach, and extended MVC design pattern which includes Presenter (also known as ViewModel).
- Installation of FuelPHP involves running a curl command, creating a project with oil, refining the install, and updating the composer to install dependencies. Fuel’s Oil is a Laravel Artisan substitute, a command line utility to facilitate quick development and run multiple tasks.
- FuelPHP packages can be shared with others and are found on Packagist, similar to all Composer packages. They can be installed manually or via Composer.
- FuelPHP uses MVC architecture, with controllers placed in specific directories and prefixed accordingly. It allows automatic routing of HTTP requests via prefix actions, and requires enabling of certain packages in the app/config/config.php file.
- The security of a FuelPHP application is enhanced by built-in features like input and URI filtering, output encoding, and a robust ORM (Object-Relational Mapping) layer that prevents SQL injection. It is suitable for both beginners and experienced developers, and is free to use for both personal and commercial projects under the MIT license.
Installation of FuelPHP Framework
To install FuelPHP, the only thing you need to do is run: curl get.fuelphp.com/oil | sh
and create your project with oil create project_name
.
There will be optional commands such as oil refine install
, which makes the necessary directories writable, and finally, do composer update
to install the dependencies.
What is FuelPHP Oil?
If you have experience with PHP frameworks, the concept of oil
will be completely clear to you. For example, Fuel’s Oil is a Laravel Artisan substitute. Indeed, oil is a command line utility to facilitate quick development, test your application, and run multiple tasks. This will enable you to speed up your development by providing several functions:
- Generate: Create MVC components, migrations, etc.
- Refine: Run tasks such as migrate, and also your own customized tasks.
- Package: Install, update and remove packages.
- Console: Test your code in real-time using an interactive shell.
- Testing: Run PHPUnit tests.
Read more about oil here.
FuelPHP Packages
Fuel has packages which allow you to share packages you build with other people. They can be found on Packagist, same as all Composer packages.
There are two ways to install a package. You can do it manually by throwing oil, or use Composer. I personally prefer the Composer approach.
You can read more about packages here.
Getting Started
As you know, Fuel uses MVC architecture like most other frameworks. Every framework has its own rules for specific mvc parts. In Fuel, controllers are placed in the fuel/app/classes/controller
directory, and are prefixed with controller_
. Optionally, they should extend the controller class for the full feature set. In Fuel, you can route HTTP requests automatically via some prefix actions, like post and get in defining a method.
Let’s get started working with Fuel basics.
Please make sure you enable the following two packages in app/config/config.php
:
'packages' => array(
'orm',
'auth'
)
We will use them in the next section. The default route is hello
, which shows your welcome page. If you would like to perform some changes, simply edit fuel/app/config/routes.php
:
return array(
'_root_' => 'welcome/index', // The default route
'_404_' => 'welcome/404', // The main 404 route
'hello(/:name)?' => array('welcome/hello', 'name' => 'hello')
);
Say Hello to FuelPHP
Now would be a good time to say hello to the world of Fuel. First, create a simple authentication app by means of Simpleauth. Simpleauth refers to a simple authentication system which is included in the auth package. To use Simpleauth, copy fuel/packages/auth/config/auth.php
and simpleauth.php
to fuel/app/config/
. Then, create a database table. I use migrations instead of traditional database operations. I would copy core/config/migrations.php
to app/config/migrations.php
and run the following command to create a scaffold :
php oil generate scaffold user username:string password:string email:string profile_fields:text created_at:string updated_at:string last_login:integer[20]
This will create a file in our app/migrations
folder named 001_create_users.php
, which I’ve edited as:
namespace Fuel\Migrations;
class 001_create_users
{
public function up()
{
\DBUtil::create_table('users', array(
'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true),
'username' => array('constraint' => 255, 'type' => 'varchar'),
'password' => array('constraint' => 255, 'type' => 'varchar'),
'email' => array('constraint' => 255, 'type' => 'varchar'),
'last_login' => array('constraint' => 20, 'type' => 'int'),
'profile_fields' => array('constraint' => 255, 'type' => 'varchar'),
'created_at' => array('constraint' => 255, 'type' => 'varchar'),
'updated_at' => array('constraint' => 255, 'type' => 'varchar')
), array('id'));
$username = "AwesomeAlireza";
$password = "@awesomeAlireza@";
$pass_hash = \Auth::instance()->hash_password($password);
$email = "Alireza@is-awesome.com";
$users = \Model_User::forge(array(
'username' => $username,
'password' => $pass_hash,
'email' => $email,
'profile_fields' => '',
'last_login' => ''
));
if ($users and $users->save())
\Cli::write("the user has been created");
else
\Cli::write("failed to create user");
}
public function down()
{
\DBUtil::drop_table('users');
}
}
To submit this, you just need to run php oil refine migrate
.
If you see this result Migrated to latest version: 1.
, it means that everything went well. After this, please create a Common controller in app/classes/controller/common.php
:
class controller_common extends Controller_Template
{
public function before()
{
parent::before();
$uri_string = explode('/', Uri::string());
$this->template->logged_in = false;
if (count($uri_string)>1 and $uri_string[0] == 'users' and $uri_string[1] == 'login')
return;
else
{
if(\Auth::check())
{
$user = \Auth::instance()->get_user_id();
$this->user_id = $user[1];
$this->template->logged_in = true;
}
else
\Response::redirect('/users/login');
}
}
}
And the user controller is located in app/classes/controller/users.php
:
class controller_users extends Controller_Common
{
public function action_index()
{
$data['users'] = Model_User::find('all');
$this->template->title = "Users";
$this->template->content = View::forge('users/index', $data);
}
public function action_login()
{
if (Auth::check())
Response::redirect('/');
$val = Validation::forge('users');
$val->add_field('username', 'Your username', 'required|min_length[3]|max_length[20]');
$val->add_field('password', 'Your password', 'required|min_length[3]|max_length[20]');
if ($val->run())
{
$auth = Auth::instance();
if ($auth->login($val->validated('username'), $val->validated('password')))
{
Session::set_flash('notice', 'FLASH: logged in');
Response::redirect('users');
}
else
{
$data['username'] = $val->validated('username');
$data['errors'] = 'Wrong username/password. Try again';
}
}
else
{
if ($_POST)
{
$data['username'] = $val->validated('username');
$data['errors'] = 'Wrong username/password combo. Try again';
}
else
{
$data['errors'] = false;
}
}
$this->template->errors = $data['errors'];
$this->template->content = View::forge('users/login')->set($data);
}
public function action_view($id = null)
{
$data['user'] = Model_User::find($id);
$this->template->title = "User";
$this->template->content = View::forge('users/view', $data);
}
public function action_logout()
{
Auth::instance()->logout();
Response::redirect('/');
}
}
As you can see, the controller extends Controller_Common
in order to be restricted by log-in. I’ve also validated my input data in the controller, but it could be in our model, too.
We’re done with controllers and it’s time to create a view for our app. In Fuel, the view files are located under app/views/CONTROLLERNAME/
. The first view we’ll create is app/views/users/login.php
:
<h2>Login</h2>
Login to your account using your username and password.
<div class="input required">
<?php isset($errors) ? $errors : false; ?>
<?php echo Form::open('users/login'); ?>
<?php echo Form::label('Username', 'username'); ?>
<?php echo Form::input('username', null, array('size' => 30)); ?>
</div>
<div class="input password required">
<?php echo Form::label('Password', 'password'); ?>
<?php echo Form::password('password', null, array('size' => 30)); ?>
</div>
<div class="submit" >
<?php echo Form::submit('login', 'Login'); ?>
</div>
And now, the index.php
file:
<div><?php echo $user->username; ?></div>
The only thing you need to do now is just navigate to https://127.0.0.1/public/users/login
in your browser and you’ll see a page like:
Congratulations, you’ve created a simple authentication app!
The code is also available on Github.
Conclusion
As you can see, Fuel has greatly simplified the path to web application construction. Each framework has its own advantages, but I hope this post has shown you some of Fuel’s, so that you may give it the chance it deserves in your toolbox.
Comments? Feedback? Let me know!
Frequently Asked Questions about FuelPHP
What is FuelPHP and how does it differ from other PHP frameworks?
FuelPHP is a flexible, full-stack PHP framework that was first released in 2011. It is built on the foundations of HMVC (Hierarchical Model-View-Controller) architecture, which allows for better organization of code and enhances scalability. Unlike other PHP frameworks, FuelPHP provides a more advanced version of the MVC design pattern that includes Presenter (also known as ViewModel) and extends the MVC pattern. It also supports a router-based approach, which means you can create specific URLs for different pages in your application.
How secure is FuelPHP?
FuelPHP comes with several built-in features that enhance security. It includes input and URI filtering and output encoding, which protect against common vulnerabilities like SQL injection and Cross-Site Scripting (XSS). It also has a powerful ORM (Object-Relational Mapping) layer that prevents SQL injection. However, like any other framework, the security of a FuelPHP application also depends on how it is used by developers.
What are the main features of FuelPHP?
FuelPHP offers a range of features that make it a powerful and flexible framework. These include its HMVC implementation, RESTful API development support, a caching system, vulnerability protection, and a modular and extendable architecture. It also includes a powerful ORM layer and supports form and data validation.
How does FuelPHP support database interactions?
FuelPHP provides a robust ORM (Object-Relational Mapping) layer for database interactions. This allows developers to interact with their database using object-oriented syntax. It supports various database platforms including MySQL, PostgreSQL, SQLite, and others.
How can I install FuelPHP?
FuelPHP can be installed using the Composer, a tool for dependency management in PHP. You can also download it directly from GitHub. After downloading, you need to configure your web server to point to the public folder of the FuelPHP installation.
Is FuelPHP suitable for beginners?
FuelPHP is a flexible and powerful framework that can be used by both beginners and experienced developers. Its documentation is comprehensive and easy to understand, making it a good choice for those new to PHP frameworks.
Can I use FuelPHP for commercial projects?
Yes, FuelPHP is open-source and free to use for both personal and commercial projects. It is licensed under the MIT license, which allows for commercial use, modification, distribution, and private use.
How is the performance of FuelPHP?
FuelPHP is known for its performance and efficiency. It is lightweight and optimized for performance, which makes it a good choice for both small and large-scale applications.
What kind of support is available for FuelPHP?
FuelPHP has a strong community support available through various platforms like StackOverflow, GitHub, and its official website. There are also numerous tutorials and resources available online to help you get started with FuelPHP.
Is FuelPHP still maintained?
Yes, FuelPHP is still actively maintained. The latest version, FuelPHP 1.8, was released in November 2018. The team is also working on the next major release, FuelPHP 2.0.
To whom it may concern, I'm Alireza. For a significant chunk of my waking hours I’m a PHP expert, Author, Speaker and independent consultant on the design of enterprise web applications with Master's degrees in Computer Science. I <3 Tech, But pass time away from computers as an aspiring amateur writer, fishing, traveling, hunting, soccer- I'm a massive Liverpool FC fan!