PHP
Article

Re-introducing FuelPHP

By Alireza Rahmani Khalili

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 http://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!

  • Steve “uru” West

    Not a bad intro to FuelPHP. One thing I notice as a potential issue though, did you mean the orm and auth packages to be in the “always load” part of the config? I don’t see any mention of this and if packages are not listed in the always load directive they have to be loaded manually.

    • Steve “uru” West

      I also notice you don’t really explain what the code is doing, it might be good to cover some of the basic functions that are being called and what they do, in addition there is no explanation on what you change in the migration and why. I also note that your class names are all lower case, is this a typo?

      I think it would also help new users if you where to list why you chose to go with fuel. If someone is looking into the framework and came across this it would be useful to see why others have chosen it.

      Aside from these small things it’s great to see more stuff being written about fuel.

      • alireza Rahmani khalili

        Thanks for feedback. the earlier version no need to mention always in package, but the current version require. in other hand I assume the developer knows basics of modern PHP frameworks like migrations and the concept of code is clear to an intermediate PHP developer

        • Steve “uru” West

          That may be but it never hurts to explain why you are doing things. I also now notice that in your common_controller you manually explode and check the URI, you can have the URI class do this for you. http://fuelphp.com/docs/classes/uri.html#/method_segment.

          It’s always good to see more stuff about fuel out there but would be nice if the information you are providing is correct for the most recent version at the time of writing.

          Again please don’t read this the wrong way, I am not attacking you, just trying to help you provide a better tutorial.

  • vee

    If you use FuelPHP, try Fuel Start https://github.com/OkveeNet/fuel-start
    It is FuelPHP backoffice with account/role/permissions control.

  • alireza Rahmani khalili

    sure. thanks for directions

  • alireza Rahmani khalili

    good spot, thank you!

  • gazugafan

    It’s awesome to see an article on FuelPHP… definitely my framework of choice. It comes with so much built-in functionality, is super-well organized, and easy to customize.

    • alireza Rahmani khalili

      Yeah you’re right man!

  • Bruno Seixas

    I know this is not in the scope of the article but here it goes…
    The first PHP Framework I used was CakePhp and I simply loved it. It was a proper relation for about 2 years ;p

    Can you share your thoughts if the framework has been improving? Or what do you think about the future version 3?

    thanks =)

    • alireza Rahmani khalili

      CakePHP is good and CakePHP 3 is great; but Always depends on your project there would be better options .For me Fuel and Laravel both are respected. I think they helped me to create my project more rapid than CakePHP and options such as Convert your FrameWork to Domain Driven Design is very easier than CakePHP. Thanks

  • Piotrek

    Nice article, but I’d like to point out that you don’t really differentiate FuelPHP from other frameworks. For example – if I’m using Silex (for smaller projects), why would I consider switching to FuelPHP? Some comparison to other popular frameworks would be appreciated.

  • Abdelbasset

    Thanks A5i that’s was a really good intro for FuelPHP
    could you please tell us how to make an authentication cross-domain using FuelPHP
    I need that for my API
    CHOKRAN

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in PHP, once a week, for free.