PHP
Article
By Alireza Rahmani Khalili

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.

--ADVERTISEMENT--

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!

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account