PhalconPHP: Yet Another PHP Framework?

There’s a wide offering of PHP frameworks, from full-stack frameworks containing ORMs, validation components, and loads of HTML helpers, to micro frameworks which go little beyond offering routing functionality. They all claim to be special, either with beautiful syntax, high speed, or good documentation. One of those frameworks is Phalcon. But Phalcon really is quite different compared to the other frameworks; it isn’t just another package that you download, rather it’s a PHP module written in C.

In this article we’ll take a brief look at what Phalcon looks like and what makes it so special.

What is Phalcon?

Phalcon is a full-stack framework. It promotes the MVC architecture and offers features like an ORM, a Request object library, a templating engine, caching, pagination… a full list of features can be found on it’s website.

But Phalcon is somewhat unique because you don’t just download an archive and extract it to a directory like you do with most other frameworks. Instead, you download and install Phalcon as a PHP module. The install process doesn’t take much more than a few minutes, and installation instructions can be found in the documentation. Also, Phalcon is open-source. You can always modify the code and recompile it if you want.

Compiled for Better Performance

One major drawback for PHP is that on every request, all files are read from the hard drive, translated into bytecode, and then executed. This causes some major performance loss when compared to other languages like Ruby (Rails) or Python (Django, Flask). With Phalcon the whole framework already is in RAM, so the whole set of framework files don’t need to process. There are benchmarks on the website that show indeed this has some significant performance advantages.

phalcon-01

Phalcon serves more than double of CodeIgniter’s requests per second. And when you look at the time per request, Phalcon takes the least amount of time to handle requests. So whenever a framework says that it’s fast, think that Phalcon is even faster.

Using Phalcon

Phalcon offers the classic features of a modern PHP MVC-framework (routing, controllers, view template, ORM, Caching, etc.), so there is nothing special when compared to other frameworks except for its speed. Still, let’s take a look at what a typical project using Phalcon looks like.
First, there’s usually a bootstrap file which will be called on every request. The requests are sent to the bootstrap via directives stored in an .htaccess file.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

The Phlacon documentation suggests using the following directory structure:

  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/

But the directory layout can be modified if you really want since everything will be accessed via the bootstrap file which exists as public/index.php.

<?php
try {
    // register an autoloader
    $loader = new PhalconLoader();
    $loader->registerDirs(array(
        '../app/controllers/',
        '../app/models/'
    ))->register();

    // create a dependency injection container
    $di = new PhalconDIFactoryDefault();

    //set up the view component
    $di->set('view', function(){
        $view = new PhalconMvcView();
        $view->setViewsDir('../app/views/');
        return $view;
    });

    // handle the request
    $application = new PhalconMvcApplication();
    $application->setDI($di);
    echo $application->handle()->getContent();
}
catch (PhalconException $e) {
     echo "PhalconException: ", $e->getMessage();
}

Model-Controller

The controllers and models are autoloaded, so you can just create files and use them from anywhere in the project. Controllers should extend PhalconMvcController and models extend PhalconMvcModel.

Controller actions are defined like so:

    public function indexAction() {
	echo 'welcome to index';
    }

Models too are pretty straight-forward:

class Users extends PhalconMvcModel
{
}

By extending the PhalconMvcModel class you immediately have access to some handy methods, like find(), save(), and validate(). And you can use relationships like:

class Users extends PhalconMvcModel
{
    public function initialize() {
        $this->hasMany('id', 'comments', 'comments_id');
    }
}

Views

Views offer basic functionality like being able to pass data to your views and working with layouts. Phalcon views doesn’t use special syntax though like Twig or Blade, though. They use pure PHP.

<html>
 <head>
  <title>Blog's title</title>
 </head>
 <body>
<?php echo $this->getContent(); ?>
 </body>
</html>

Phalcon does however has a flash messaging system built-in:

$this->flashSession->success('Succesfully logged in!');

Phalcon Query Language

Phalcon has its own ORM, Phalcon Query Language (PHQL), which can be used to make database interaction more expressive and clean. PHQL can be integrated with models to easily define and use relationships between your tables.

You can use PHQL by extending the PhalconMvcModelQuery class and then create a new query like:

$query = new PhalconMvcModelQuery("SELECT * FROM Users", $di);
$users = $query->execute(); 

And instead of such raw SQL, you can use the query builder like this:

$users = $this->modelsManager->createBuilder()->from('Users')->orderBy('username')->getQuery()->execute();

This can come in quite handy when your queries get more complicated.

Conclusion

Phalcon offers the classic features of a modern PHP MVC-framework so it should be comfortable to use, so in that sense it is just another PHP framework. But where it really stands out from the others is its speed. If you’re are interested in learning more about Phalcon, check out the framework’s documentation. Make sure you try it out!

Image via Fotolia

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Joãp

    Looks interesting, usually when I see these posts I think to myself “great, another PHP MVC framework…”, but if those benchmarks are correct and the whole framework is “already is in RAM”, this could be very interesting indeed.

    Combine the above with the simple syntax (none of that Blade crap and weird PHP syntax – hey, it’s PHP, if you don’t like it’s weirndess ;)…), it’s actually something I’m going to keep my eyes on.

  • http://r.je Tom B

    Impressive speed, but anything that uses a PHP extension instead of PHP code will be faster. It’s disappointing to see yet another “MVC” framework that doesn’t understand the concept of MVC though.

    • Attila Fulop

      What do you mean on “doesn’t understand the concept of MVC”?

      • http://r.je Tom B

        The same as most of the PHP frameworks which incorrectly label themselves “MVC”:
        -Using the controller as a gateway between models and views
        -Ignoring the concept of application state by use of stateless models and replacing it with controller actions which have to compensate for this, as well as communicating the state to the view.
        -Fat controllers, thin models

        • Mike Howell

          @Tom B
          I am not sure you are being fair to PHP frameworks. Sure, they offer a built in use case for stateless models, or one and done models, but honestly so does nearly every MVC framework including enterprise frameworks such as Java Spring. It all comes down to a model being a service (or data access object) vs an actual resource in memory that is stateful.

          We could debate all day what is the right way but at the end of the day it all comes down to specific domain needs and just making sure the separation of concerns is met to its fullest in that regard.

          • http://r.je Tom B

            While I agree with the sentiment, the way that most PHP frameworks structure their code is far from ideal from a separation of concerns perspective. That said, I don’t care what architecture is in use but incorrectly applying the “MVC” label to something which isn’t MVC is not helpful for anyone and is part of the reason almost PHP frameworks provide a sloppy architecture: it’s difficult for anyone in the PHP/web community to find any information on MVC because a variation of a PAC architecture is labelled as MVC in almost every tutorial and book. The fact the frameworks do the same only makes this issue worse.

  • http://www.geekzeitung.com Machin

    I might give it a try, I’m looking for something to “replace” CI, as I don’t see any future there.

  • Clint

    Couldn’t figure out how to compile it on my Amazon Linux AMI on EC2 micro instance running PHP 5.4.20 .. but yeah.. I will try it again when I get some time.. The speed is killer!

    • mudit

      have you find how to setup this framework on Amazon Linux AMI on EC2…please share if you have idea about it

  • kAlmAcetA

    long time ago was founded Yaf (http://www.yafdev.com/) – first framework as a module. And what – nothing… There is no comparison of both.

  • Emily

    Were you comparing Laravel 3 or Laravel 4?
    As a Laravel user, how would you say the PHQL compares to Laravel’s Query Builder for ease of use?
    What kind of staying power do the two have? They are both being regularly updated.

  • Jordi

    Phalcon is simply fantastic. Not only for the reason that is a framework in a C library, but also for his features. The MVC pattern and all his modules are very well implemented, especially I like the ultra-fast Volt templating engine and de ODM for Mongo. Thanks for the post!

  • Philipp

    I’ve been using Phalcon since the first stable release and it really is a very good framework both in terms of performance and comfort. I’d swap the ZF stuff I have to use at work at any time for Phalcon and all my new private projects are based on Phalcon.

  • http://www.bitfalls.com Bruno Skvorc

    I’ve built 17 production websites with Phalcon and I’ll never work in another framework again. Been working in it for about a year now and it’s been a blast, and I’ve built commercial projects in all popular frameworks.

  • http://quran.2index.net Said Bakr

    There is a problem. It may not work with shared hosting service.

  • Anggiajuang Patria

    Switch to Phalcon on progress…

  • http://www.zachis.it/blog Zach Smith

    i will be back for more articles like this :)

  • Dan

    It would make more sense to benchmark against other PHP frameworks that have APC cache enabled (which should always be enabled, specially on high-performance PHP environments). This way we would be comparing apples to apples and we would know how much faster Phalcon can really be as a compiled PHP extension. Those benchmarks are mostly comparing the time PHP takes to fetch files, parse and convert to bytecode.

    Perhaps PHP+APC+Phalcon would be even faster, if it saves the fetching/parsing/converting to bytecode steps?

  • https://github.com/laruence/php-yaf FightingMan

    Yaf https://github.com/laruence/php-yaf is the most fast framework

  • http://www.bitfalls.com/ Bruno Skvorc

    Their homepage and all the examples on it are running Phalcon. My own work can be seen here: autosusados.hn (and other links in footer), but dev mode is still on so no caching and CDN is off, might be slower than it should.