Re-introducing FuelPHP

Share this article

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.

FuelPHP

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.

Alireza Rahmani KhaliliAlireza Rahmani Khalili
View Author

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!

BrunoSFrameworksfuelphpOOPHPPHP
Share this article
Read Next
7 Easy Ways to Make a Magento 2 Website Faster
7 Easy Ways to Make a Magento 2 Website Faster
Konstantin Gerasimov
Powerful React Form Builders to Consider in 2024
Powerful React Form Builders to Consider in 2024
Femi Akinyemi
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Quick Tip: How to Animate Text Gradients and Patterns in CSS
Ralph Mason
Sending Email Using Node.js
Sending Email Using Node.js
Craig Buckler
Creating a Navbar in React
Creating a Navbar in React
Vidura Senevirathne
A Complete Guide to CSS Logical Properties, with Cheat Sheet
A Complete Guide to CSS Logical Properties, with Cheat Sheet
Ralph Mason
Using JSON Web Tokens with Node.js
Using JSON Web Tokens with Node.js
Lakindu Hewawasam
How to Build a Simple Web Server with Node.js
How to Build a Simple Web Server with Node.js
Chameera Dulanga
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Building a Digital Fortress: How to Strengthen DNS Against DDoS Attacks?
Beloslava Petrova
Crafting Interactive Scatter Plots with Plotly
Crafting Interactive Scatter Plots with Plotly
Binara Prabhanga
GenAI: How to Reduce Cost with Prompt Compression Techniques
GenAI: How to Reduce Cost with Prompt Compression Techniques
Suvoraj Biswas
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
How to Use jQuery’s ajax() Function for Asynchronous HTTP Requests
Aurelio De RosaMaria Antonietta Perna
Quick Tip: How to Align Column Rows with CSS Subgrid
Quick Tip: How to Align Column Rows with CSS Subgrid
Ralph Mason
15 Top Web Design Tools & Resources To Try in 2024
15 Top Web Design Tools & Resources To Try in 2024
SitePoint Sponsors
7 Simple Rules for Better Data Visualization
7 Simple Rules for Better Data Visualization
Mariia Merkulova
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
Cloudways Autonomous: Fully-Managed Scalable WordPress Hosting
SitePoint Team
Best Programming Language for AI
Best Programming Language for AI
Lucero del Alba
Quick Tip: How to Add Gradient Effects and Patterns to Text
Quick Tip: How to Add Gradient Effects and Patterns to Text
Ralph Mason
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Logging Made Easy: A Beginner’s Guide to Winston in Node.js
Vultr
How to Optimize Website Content for Featured Snippets
How to Optimize Website Content for Featured Snippets
Dipen Visavadiya
Psychology and UX: Decoding the Science Behind User Clicks
Psychology and UX: Decoding the Science Behind User Clicks
Tanya Kumari
Build a Full-stack App with Node.js and htmx
Build a Full-stack App with Node.js and htmx
James Hibbard
Digital Transformation with AI: The Benefits and Challenges
Digital Transformation with AI: The Benefits and Challenges
Priyanka Prajapat
Quick Tip: Creating a Date Picker in React
Quick Tip: Creating a Date Picker in React
Dianne Pena
How to Create Interactive Animations Using React Spring
How to Create Interactive Animations Using React Spring
Yemi Ojedapo
10 Reasons to Love Google Docs
10 Reasons to Love Google Docs
Joshua KrausZain Zaidi
How to Use Magento 2 for International Ecommerce Success
How to Use Magento 2 for International Ecommerce Success
Mitul Patel
5 Exciting New JavaScript Features in 2024
5 Exciting New JavaScript Features in 2024
Olivia GibsonDarren Jones
Tools and Strategies for Efficient Web Project Management
Tools and Strategies for Efficient Web Project Management
Juliet Ofoegbu
Choosing the Best WordPress CRM Plugin for Your Business
Choosing the Best WordPress CRM Plugin for Your Business
Neve Wilkinson
ChatGPT Plugins for Marketing Success
ChatGPT Plugins for Marketing Success
Neil Jordan
Managing Static Files in Django: A Comprehensive Guide
Managing Static Files in Django: A Comprehensive Guide
Kabaki Antony
The Ultimate Guide to Choosing the Best React Website Builder
The Ultimate Guide to Choosing the Best React Website Builder
Dianne Pena
Exploring the Creative Power of CSS Filters and Blending
Exploring the Creative Power of CSS Filters and Blending
Joan Ayebola
How to Use WebSockets in Node.js to Create Real-time Apps
How to Use WebSockets in Node.js to Create Real-time Apps
Craig Buckler
Best Node.js Framework Choices for Modern App Development
Best Node.js Framework Choices for Modern App Development
Dianne Pena
SaaS Boilerplates: What They Are, And 10 of the Best
SaaS Boilerplates: What They Are, And 10 of the Best
Zain Zaidi
Understanding Cookies and Sessions in React
Understanding Cookies and Sessions in React
Blessing Ene Anyebe
Enhanced Internationalization (i18n) in Next.js 14
Enhanced Internationalization (i18n) in Next.js 14
Emmanuel Onyeyaforo
Essential React Native Performance Tips and Tricks
Essential React Native Performance Tips and Tricks
Shaik Mukthahar
How to Use Server-sent Events in Node.js
How to Use Server-sent Events in Node.js
Craig Buckler
Five Simple Ways to Boost a WooCommerce Site’s Performance
Five Simple Ways to Boost a WooCommerce Site’s Performance
Palash Ghosh
Elevate Your Online Store with Top WooCommerce Plugins
Elevate Your Online Store with Top WooCommerce Plugins
Dianne Pena
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Unleash Your Website’s Potential: Top 5 SEO Tools of 2024
Dianne Pena
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
How to Build a Chat Interface using Gradio & Vultr Cloud GPU
Vultr
Enhance Your React Apps with ShadCn Utilities and Components
Enhance Your React Apps with ShadCn Utilities and Components
David Jaja
10 Best Create React App Alternatives for Different Use Cases
10 Best Create React App Alternatives for Different Use Cases
Zain Zaidi
Control Lazy Load, Infinite Scroll and Animations in React
Control Lazy Load, Infinite Scroll and Animations in React
Blessing Ene Anyebe
Building a Research Assistant Tool with AI and JavaScript
Building a Research Assistant Tool with AI and JavaScript
Mahmud Adeleye
Understanding React useEffect
Understanding React useEffect
Dianne Pena
Web Design Trends to Watch in 2024
Web Design Trends to Watch in 2024
Juliet Ofoegbu
Building a 3D Card Flip Animation with CSS Houdini
Building a 3D Card Flip Animation with CSS Houdini
Fred Zugs
How to Use ChatGPT in an Unavailable Country
How to Use ChatGPT in an Unavailable Country
Dianne Pena
An Introduction to Node.js Multithreading
An Introduction to Node.js Multithreading
Craig Buckler
How to Boost WordPress Security and Protect Your SEO Ranking
How to Boost WordPress Security and Protect Your SEO Ranking
Jaya Iyer
Understanding How ChatGPT Maintains Context
Understanding How ChatGPT Maintains Context
Dianne Pena
Building Interactive Data Visualizations with D3.js and React
Building Interactive Data Visualizations with D3.js and React
Oluwabusayo Jacobs
JavaScript vs Python: Which One Should You Learn First?
JavaScript vs Python: Which One Should You Learn First?
Olivia GibsonDarren Jones
13 Best Books, Courses and Communities for Learning React
13 Best Books, Courses and Communities for Learning React
Zain Zaidi
5 jQuery.each() Function Examples
5 jQuery.each() Function Examples
Florian RapplJames Hibbard
Implementing User Authentication in React Apps with Appwrite
Implementing User Authentication in React Apps with Appwrite
Yemi Ojedapo
AI-Powered Search Engine With Milvus Vector Database on Vultr
AI-Powered Search Engine With Milvus Vector Database on Vultr
Vultr
Understanding Signals in Django
Understanding Signals in Django
Kabaki Antony
Why React Icons May Be the Only Icon Library You Need
Why React Icons May Be the Only Icon Library You Need
Zain Zaidi
View Transitions in Astro
View Transitions in Astro
Tamas Piros
Getting Started with Content Collections in Astro
Getting Started with Content Collections in Astro
Tamas Piros
What Does the Java Virtual Machine Do All Day?
What Does the Java Virtual Machine Do All Day?
Peter Kessler
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Become a Freelance Web Developer on Fiverr: Ultimate Guide
Mayank Singh
Layouts in Astro
Layouts in Astro
Tamas Piros
.NET 8: Blazor Render Modes Explained
.NET 8: Blazor Render Modes Explained
Peter De Tender
Mastering Node CSV
Mastering Node CSV
Dianne Pena
A Beginner’s Guide to SvelteKit
A Beginner’s Guide to SvelteKit
Erik KückelheimSimon Holthausen
Brighten Up Your Astro Site with KwesForms and Rive
Brighten Up Your Astro Site with KwesForms and Rive
Paul Scanlon
Which Programming Language Should I Learn First in 2024?
Which Programming Language Should I Learn First in 2024?
Joel Falconer
Managing PHP Versions with Laravel Herd
Managing PHP Versions with Laravel Herd
Dianne Pena
Accelerating the Cloud: The Final Steps
Accelerating the Cloud: The Final Steps
Dave Neary
An Alphebetized List of MIME Types
An Alphebetized List of MIME Types
Dianne Pena
The Best PHP Frameworks for 2024
The Best PHP Frameworks for 2024
Claudio Ribeiro
11 Best WordPress Themes for Developers & Designers in 2024
11 Best WordPress Themes for Developers & Designers in 2024
SitePoint Sponsors
Top 10 Best WordPress AI Plugins of 2024
Top 10 Best WordPress AI Plugins of 2024
Dianne Pena
20+ Tools for Node.js Development in 2024
20+ Tools for Node.js Development in 2024
Dianne Pena
The Best Figma Plugins to Enhance Your Design Workflow in 2024
The Best Figma Plugins to Enhance Your Design Workflow in 2024
Dianne Pena
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Harnessing the Power of Zenserp for Advanced Search Engine Parsing
Christopher Collins
Build Your Own AI Tools in Python Using the OpenAI API
Build Your Own AI Tools in Python Using the OpenAI API
Zain Zaidi
The Best React Chart Libraries for Data Visualization in 2024
The Best React Chart Libraries for Data Visualization in 2024
Dianne Pena
7 Free AI Logo Generators to Get Started
7 Free AI Logo Generators to Get Started
Zain Zaidi
Turn Your Vue App into an Offline-ready Progressive Web App
Turn Your Vue App into an Offline-ready Progressive Web App
Imran Alam
Clean Architecture: Theming with Tailwind and CSS Variables
Clean Architecture: Theming with Tailwind and CSS Variables
Emmanuel Onyeyaforo
How to Analyze Large Text Datasets with LangChain and Python
How to Analyze Large Text Datasets with LangChain and Python
Matt Nikonorov
6 Techniques for Conditional Rendering in React, with Examples
6 Techniques for Conditional Rendering in React, with Examples
Yemi Ojedapo
Introducing STRICH: Barcode Scanning for Web Apps
Introducing STRICH: Barcode Scanning for Web Apps
Alex Suzuki
Using Nodemon and Watch in Node.js for Live Restarts
Using Nodemon and Watch in Node.js for Live Restarts
Craig Buckler
Task Automation and Debugging with AI-Powered Tools
Task Automation and Debugging with AI-Powered Tools
Timi Omoyeni
Quick Tip: Understanding React Tooltip
Quick Tip: Understanding React Tooltip
Dianne Pena
12 Outstanding AI Tools that Enhance Efficiency & Productivity
12 Outstanding AI Tools that Enhance Efficiency & Productivity
Ilija Sekulov
React Performance Optimization
React Performance Optimization
Blessing Ene Anyebe
Introducing Chatbots and Large Language Models (LLMs)
Introducing Chatbots and Large Language Models (LLMs)
Timi Omoyeni
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Migrate to Ampere on OCI with Heterogeneous Kubernetes Clusters
Ampere Computing
Scale Your React App with Storybook and Chromatic
Scale Your React App with Storybook and Chromatic
Daine Mawer
10 Tips for Implementing Webflow On-page SEO
10 Tips for Implementing Webflow On-page SEO
Milan Vracar
Get the freshest news and resources for developers, designers and digital creators in your inbox each week