loading...
Cover image for A comparison between Laravel and Phalcon

A comparison between Laravel and Phalcon

adnanbabakan profile image Adnan Babakan (he/him) Updated on ・14 min read

Hey there DEV.to community!

Recently I was working on a personal project and a commercial one. Since I had some basic knowledge about Laravel and have used it before I decided to have Laravel as my framework for my commercial project and Phalcon for my personal project so even if I ruin it would be compensable.

There is a Vietnamese version of this article available at http://www.web68.vn/vi/p/so-sanh-laravel-va-phalcon-47328.html thanks to:

genievn image

I highly suggest you to use a framework you already know on a commercial project unless you would get in a big trouble!

Laravel is the most famous framework right now and Phalcon is the fastest one so far. So these two are the greatest ones i my opinion. Let's be clear that Symfony, Yii, Cake or Code Igniter or other frameworks are great too but this post will be based on Laravel and Phalcon since I used them both till I gain some knowledge about them that I can make a basic comparison.

To be clear, at the time I'm writing this article I'm using Laravel 6 which is the latest version and Phalcon 3.4.

This article will be point based and at the end of each section I will point one or both of frameworks and at the end we will see what the results are.

Note: If you are not in the mood to read all the article just follow the points!

This will be an unbiased comparison since I'm not owner of any of these neither I'm funded by any. I'm just a simple programmer.

Keep in mind that this isn't a deep comparison and I will try to keep each section as brief as possible meanwhile informative.

Dog

This has nothing to do with the article

Setup and getting started

Let's get on from the beginning! What you do when you want to start a project is setting up the environment so you can code your ideas (I hate .idea folder when I push it to my git repository LOL).

Laravel and Phalcon are no exception.

Setting up Laravel is pretty easy and what you need to do is installing its package using composer and using the laravel command to start a new project. Or even you don't have access to composer you can simply copy and paste Laravel's files and start coding.

We'll since Phalcon is a little bit different and isn't actually written in PHP itself and is a C-extension indeed (though you will be writing PHP from 0 to 100) you need to install it on your server or local server in order to be able to use it which requires compiling or downloading the pre-compiled version of the extension and enable it on your web server using some manual configurations which is a pain if you don't know how to do so. Except for that Phalcon also provides a tools called Phalcon DevTools which helps you to create a project and start coding.

But using laravel new command takes you a little bit of time which is way more than phalcon create-project overall since Laravel installs some packages which it needs in order to run but Phalcon instantly creates the structure needed.

Since Phalcon's setup is a little bit complicated the point from this section goes to Laravel!

Laravel: 1
Phalcon: 0

File structure

Something that might be very important for lots of programmers is the file structure the framework provides by default.

So Laravel is actually very well organized but have some problems in my opinion. First the models are located under the app folder's root which has some other folders in it used for controller and other things as well. This isn't that clean.
Other than that the file structure could have been a lot better in some other parts.
And Laravel is a heavy framework due to so many files it has by default.

Phalcon is a bit different than all other frameworks. Since it is installed as a C-extension on the server you don't have any files related to Phalcon on your project and that keeps it really clean and simple. You can design your own pattern with Phalcon or use the default one provided by Phalcon DevTools.
So literally you only have the files you need on you project and nothing more which makes it more efficient when uploading it or transferring it anyhow.

Phalcon fresh project file structure

This is a fresh Phalcon project's file structure created using Phalcon DevTools

Phalcon fresh project tree

This is a tree of the same Phalcon project as above

Laravel fresh project file stricture

This is a fresh Laravel project's file structure created using Laravel CLI

Unfortunately, Laravel's tree was too long to be able to be screenshotted (don't know even if this tense exists LOL) so I couldn't upload it but you all know how it is!

The point from this section goes to Phalcon absolutely.

Laravel: 1
Phalcon: 1

Speed and performance

So this is always one of the most important things to be asked when choosing a framework.

So let's do some basic calculations. PHP is a language written using C and C++ for some components which is a very fast language but PHP itself is a bit (actually a lot) slower than C/C++ and it is a very obvious thing. So since Laravel's core is written in PHP it is still slower than C itself but Phalcon is written in C and doesn't need to be interpreted at least for its core functionality because it is already done! This will obviously makes Phalcon faster, fast as hell!

PHP Frameworks speed comparison

Credits for image: https://systemsarchitectdotnet.wordpress.com/2013/04/23/performance-benchmark-of-popular-php-frameworks/

The image above shows how fast Phalcon is comparing to all other frameworks.

The point from this section absolutely goes to Phalcon again.

Laravel: 1
Phalcon: 2

Complexity

The next major thing about a framework is its learning curve! How long it takes to learn it as enough as you would be able to write an application with it is an important matter.

Laravel is known for its documentations and for thousands of tutorials there are for it which makes it really easy to learn. Laravel's commenting is one of the best things ever happened for every PHP programmer.
Laravel is very well understood and is comprehensible even for new users.

Phalcon provides a good documentation on their official website but to be honest it is kind of complicated already for advanced users so never mind it how a new user would feel reading Phalcon's documentation. Phalcon also has some video tutorials available but not as many as Laravel has.
Since Phalcon doesn't have its files on your project you don't get any commenting on how it works.

The point for this section is Laravel's for sure.

Laravel: 2
Phalcon: 2

Architecture

Almost all modern frameworks use MVC (model-view-controller) architecture since it is very easy to use and is accepted amongst the programmers' community.

Laravel also makes use of MVC and provides a very good demonstration of it. But what is bad about MVC is if your application is growing too big you are in a big problem with MVC and that's when HMVC (Hierarchical model–view–controller) comes to save the world!

HMVC is simply MVC but in the component-ordered base. Assume you have a website that has a blog and a forum part. HMVC divides these two parts into MVC components so you can have each of them separately developed but used as one!

Phalcon allows you to implement such an architecture on your project which Laravel doesn't.

Although HMVC is rarely used compared to MVC but still it is a feature that we can count on.

The point in Phalcon's.

Laravel: 2
Phalcon: 3

Database integration

Databases are a crucial part of each and every application doesn't matter web or desktop based.

Both Laravel and Phalcon provide good solutions. A usual one is using an ORM which stands for Object-relational mapping and is used to control the data from or to the database more easily.

Laravel has Eloquent in order to take advantage of your models and Phalcon also provides a similar tool as well but I have to confess Eloquent is way more featured and easier to use.

Something that is similar to an ORM is ODM (Object-document mapping) which is usually used for NoSQL databases such as MongoDB. Unfortunately, Laravel doesn't have the support of ODMs out of the box but can be added using some other packages. On the other hand, Phalcon gives you some tools to get your application working with your MongoDB out of the box.

Since Laravel has a rich ORM and Phalcon provides ODM as well as ORM I think they both deserve to get the point!

Laravel: 3
Phalcon: 4

Routing and Controllers

A web application is all about routing and nothing more!

Both frameworks provide some methods to implement the desired routes for your application. Both are capable of handling all common HTTP methods such as POST and GET (these are the most common ones I believe).

Laravel's routing is very very easy to use and you'd think Laravel already knows what you want and provide you with the necessary ingredient to make your routes come alive.

Phalcon on the other is very harsh about routing. A very simple thing I had a problem with Phalcon's routing is its lack of optional parameters which had me make two routes one with the parameter and the other one without it.

Both of these frameworks support prefixing and grouping routes. Laravel additionally supports sub-domain routing which Phalcon doesn't.

Phalcon router config sample:

<?php

use Phalcon\Mvc\Router\Group as RouterGroup;

$router = $di->getRouter(false);
$router->removeExtraSlashes(true);

//X User Routing Group
$x_user = new RouterGroup(['controller' => 'XUser']);
$x_user->setPrefix('/x');
$router->add('/x', ['controller' => 'XUser', 'action' => 'home']);
$x_user->add('/login', ['action' => 'login'])->setName('login');
$x_user->add('/logout', ['action' => 'logout'])->setName('logout');
$x_user->add('/sign-up', ['action' => 'signUp'])->setName('sign-up');
$x_user->add('/remember-me', ['action' => 'remember'])->setName('remember-me');
$x_user->add('/verify', ['action' => 'verifyAccount'])->setName('verify-account');
$x_user->add('/profile', ['action' => 'profile'])->setName('profile');
$router->mount($x_user);
Enter fullscreen mode Exit fullscreen mode

Laravel router config sample:

<?php

use App\Category;
use App\Mail\ResetPassword;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;

Route::get('/', 'GeneralController@home');

Route::prefix('/user')->group(function () {
    Route::post('/sign-up', 'UserController@signUp');
    Route::post('/login', 'UserController@login');
    Route::get('/logout', 'UserController@logout');
    Route::post('/forget-password', 'UserController@forgetPassword');
    Route::get('/reset-password', 'UserController@resetPasswordLanding');
    Route::get('/verify-email', 'UserController@verifyEmail');
    Route::get('/profile/{username}', 'UserController@profile');
});
Enter fullscreen mode Exit fullscreen mode

So obviously Laravel has the upper hand in this section and gains the point. She deserves it. (I have no idea why but I always imagined Laravel as a girl and Phalcon as a boy)

Laravel: 4
Phalcon: 4

Template engines

When talking about an application it should have a front-end for the user to see and that is also one of the most important parts of every application.

Template engines are some tools that help you connect your back-end logic to the HTML/CSS and maybe JavaScript of your application with more ease.

Laravel provides a powerful template engine called Blade and Phalcon takes advantage of Volt which is a kind of Twig (from Symfony) but simpler and pre-compiled.

Both Blade and Volt are great tools but Blade is more convenient to use due to its diverse functions and methods available.

Volt is way faster out of the box since it pre-compiled so we should take this in credit as well.

Blade can be also cached to be run faster but that's something you need to tell Laravel to do.

Volt template file sample:

{% extends 'layouts/main.volt' %}

{% block title %} - صفحه {{ page_number }}{% endblock %}

{% block content %}
    <div class="row">
        <div class="columns large-9 small-12">
            <div class="widget">
                <div class="widget-title"><span>آخرین مطالب - صفحه {{ page_number }}</span></div>
                <div id="recent-posts">
                    {% for post in posts.items %}
                        <div class="post{% if post.important %} important{% endif %}">
                            <a href="{{ post.postLink() }}"><img src="{{ post.featured_image }}" alt="{{ post.title }}"
                                                                 class="cover"/></a>
                            <div class="content">
                                <div class="post-type">
                                    {% if post.categories.parent_id != 0 %}
                                        <?php $parent_category = \iCriticize\Models\Categories::findFirst(["id = '{$post->categories->parent_id}'"]); ?>
                                        <a href="{{ parent_category.categoryLink() }}"
                                           class="category">{{ parent_category.name }}</a>
                                    {% endif %}
                                    <a href="{{ post.categories.categoryLink() }}"
                                       class="category">{{ post.categories.name }}</a>
                                </div>
                                <h3><a href="{{ post.postLink() }}">{{ post.title }}</a></h3>
                                <div class="info">
                                    <i class="la la-user"></i> {{ post.users.nickname }}
                                    <i class="la la-calendar"></i> {{ post.shortPublishDate() }}
                                    <i class="la la-clock-o"></i> {{ post.publishTime() }}
                                    <i class="la la-comments-o"></i> {{ post.commentsCount() }}
                                </div>
                                <p class="preview">
                                    {{ post.preview() }}
                                </p>
                            </div>
                        </div>
                    {% endfor %}
                </div>
                {% include 'UserEnd/includes/pagination.volt' %}
            </div>
        </div>
        <div class="columns large-3 small-12">
            <div class="widget full-height">
                {% include 'UserEnd/includes/sidebar.volt' %}
            </div>
        </div>
    </div>
{% endblock %}

{% block footer_scripts %}
    <script src="{{ settings.site_address }}/bundles/home.bundle.js"></script>
{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Blade template file sample (Vue.js is also used in this file):

@extends('layouts.main')

@section('title')
    {{$user->first_name}} {{$user->last_name}} ({{$user->username}})'s Profile
@endsection

@section('content')
    <app-profile :user-info='{!! $user !!}' avatar="{{$user_private_info->getAvatar()}}"
                 member-since="{{$user_private_info->signUpDate()['month_name']}} of {{$user_private_info->signUpDate()['year']}}"
                 @if($user->account_type == "Employer"):user-projects='{!! json_encode(array_slice($user->employerProjects->toArray(), 0, 5)) !!} '
                 @endif
                 @if($user->account_type == "Freelancer"):user-projects='{!! json_encode(array_slice($user->freeLancerProjects()->toArray(), 0, 5)) !!}'@endif></app-profile>
@endsection

Enter fullscreen mode Exit fullscreen mode

Honestly what we need from a template engine is to help us get over with front-end and that's what Blade and Volt both do very well but I find Volt way cleaner than blade.

The point is Volt's. Sorry Phalcon's XD.

Laravel: 4
Phalcon: 5

I18n

An application might need to be internationalized and without proper tools, it might be really hard to do so.

This is not a crucial part of an application usually, but still, it is honourable to be mentioned.

Both frameworks are good in this case so they both get a point.

Laravel: 5
Phalcon: 6

Security

Security is the thing that will change your life if you do it either good or bad.

When writing an application it is almost your full responsibility to make sure no one can cheat or use your application's functionality in another way than they are intended to be.

Both frameworks are great in the field of security and handle almost every kind of attack pretty well. Especially more common attacks like XSS and SQL injection.

SQL injection meme

This meme is from Phalcon's sanitizing and filtering documentation

This pic has got into my mind so bad that every time I write something related to the database I laugh so hard that everyone around me looks at me as if I'm crazy (maybe I am).

And there is another "But" again here. Laravel provides a better way of handling CSRF token and using it but Phalcon is a little bit more awkward and needs a little bit more setup.

The point goes to Laravel in this section.

Laravel: 6
Phalcon: 6

Middlewares

So what you need when you want to run a task each and every time a user makes a request to your application? Of course a middleware!

So middlewares are also crucial in more complex applications.

In this case, Laravel wins instantly since Phalcon doesn't support middlewares. At least as we expect them.

You can, of course, use the controller to run some task before every route, like by defining a base controller and using its __construct() method but that's not how I expect it to be actually.

Laravel: 7
Phalcon: 6

RESTful API

Some programmers use back-end frameworks only for their API and designing a RESTful API system.

So Laravel basically supports this claim (which you better use Lumen since using Laravel only for this approach on the small-scale application would be overpowered) and provides you good tools in order to do your work including axios with csrf token support.

What I had to do with Phalcon was manipulating the response of my API controller to turn it to JSON (which Laravel does by default) and update my CSRF token as well so the next request wouldn't encounter an error.

This is what I have done in Phalcon:

<?php

namespace iCriticize\Controllers;

class ApiController extends BaseController
{

    public function beforeExecuteRoute()
    {
        $this->response->setHeader('Content-Type', 'application/json');

        if (!$this->security->checkToken()) {
            if ($this->dispatcher->getActionName() != "APITokenInvalid" and $this->dispatcher->getActionName() != "APITimeLimitReached") {
                $this->dispatcher->forward(["action" => "APITokenInvalid"]);
            }
        } else {
            if ($this->session->has('last_api_request_time')) {
                if ($this->session->get('last_api_request_time') < time() - 1) {
                    $this->session->set('last_api_request_time', time());
                } else {
                    if ($this->dispatcher->getActionName() != "APITimeLimitReached") {
                        $this->dispatcher->forward(["action" => "APITimeLimitReached"]);
                    }
                }
            } else {
                $this->session->set('last_api_request_time', time());
            }
        }
    }

    public function afterExecuteRoute()
    {
        $this->view->disable();
        $data = json_decode(json_encode($this->dispatcher->getReturnedValue()), true);
        $data["csrf_token_update"] = [$this->security->getTokenKey() => $this->security->getToken()];
        $data = json_encode($data);
        $this->response->setContent($data);
        return $this->response->send();
    }

    public function APITimeLimitReachedAction()
    {
        return ["status" => "ERR_API_REQUEST_TIME_LIMIT_REACHED"];
    }

    public function APITokenInvalidAction()
    {
        return ["status" => "ERR_API_TOKEN_INVALID"];
    }

}
Enter fullscreen mode Exit fullscreen mode

So the point is obviously going to Laravel.

Laravel: 8
Phalcon: 6

Customization

Once it comes to more advanced usage and when you want to extend the use of your framework Phalcon has the upper hand with Zephir, A high-level programming language which is used to write extensions for PHP by PHP programmers with no knowledge of C.

So when you are customizing Phalcon you still save the speed advantage of Phalcon but if you want to extend the usage of Laravel you need to use PHP which will add more tasks to be run on your application and that damages the speed thing.

Phalcon is the winner in this section.

Laravel: 8
Phalcon: 7

Community

What happens when you get stuck when writing an application? You search Google which highly likely will result in StackOverflow (what do StackOverflow engineers do when they get stuck and StackOverflow is down BTW?) and that's when a community is important. As big the community is your problems are smaller.

When the community is big, more people have probably encountered your problem before, thus it is more likely that there would be a solution already.

Laravel has a great and big community of programmers so Laravel is the winner here.

Laravel: 9
Phalcon: 7

Ease of use

So this is the part where Laravel is again known for. Laravel is good to start with since it promotes good coding behaviour along with simple ways to do so which are easy to learn.

Phalcon is more for advanced users which feel Laravel is too magic for them (magic is a term used for the work that the programmer doesn't see and the framework takes care of it).

Since the section is about the ease of use Laravel is the winner.

Laravel: 10
Phalcon: 7

Coding style

We'll this is a very personal point of view and opinion but since I work with JavaScript almost every day and I find its coding style way cleaner I think Phalcon also follows the same concept.

Phalcon is more cleaner when writing codes and is more understandable if someone else looks at your code for the first time.

The pattern Phalcon provides is much cleaner in the config files and all other stuff.

So the point here goes to Phalcon.

Laravel: 10
Phalcon: 8

Deployment

The last point of designing and programming an application is getting it to work. If you can't do this then all that you've done is actually nothing.

This step is one of the most important steps when programming an application from 0 to 100.

Laravel is supported by almost 90% of shared hosting services since it doesn't need lots of options and what is needed is usually already installed on all the hosting services. You just need to upload Laravel. Some hosting service providers provide some more advanced tools like SSH that can help you deploy your Laravel application more easily but it is not necessary.

Deploying a Phalcon application is no harder than Laravel and maybe even easier if you find a hosting that has Phalcon extension installed on their servers. If not, you would have to get a VPS (or a dedicated server if needed) in order to deploy your Phalcon application and that includes all the configuration needed for a simple plain web server and compiling and installing Phalcon.

Overall, deploying a Phalcon application would cost you more by the mean of money and time than a Laravel application.

So the point is of course Laravel's.

Laravel: 11
Phalcon: 8

Front-end assets

This section is actually only a honourable mention since it isn't that much related to the framework itself.

Using Laravel is very pleasant when trying to bundle assets using Webpack which is done using Laravel Mix but Phalcon doesn't have such a tool.

Laravel also supports Vue and React along with Bootstrap out of the box.

Phalcon has no idea about what front-end is LOL.

So the invisible point goes to Laravel.

Conclusion

Final results:

Laravel: 11
Phalcon: 8

So the last result is that Laravel is the winner here but not with a huge score difference actually.

I would still use Phalcon if I'm certain about the deployment despite all the difficulties it has it is still way way way way faster than all other frameworks.

Again keep in mind that these are all my personal experiences and yours might the different and I respect everyone's opinion.

Please let me know what your experience or opinion is in the comments section below.

If you want to know how it was like to come back to PHP after being with Node.js for a while read my article below:

Hope you enjoyed the article!

Discussion

pic
Editor guide
Collapse
fakharak profile image
Fakhar Anwar

Laravel architecture is monolithic, resource-hungry and does not scale well, while Phalcon has a reasonably good documentation and can be fused with Swoole PHP (Asynchrnous PHP Extension that allows its own HTTP server). If you like you can use parts of Laravel with Phalcon (if you are easy with Laravel, and want speed in some parts)

Selling Laravel only because it has more documentation material is not wisdom that one should expect from Software Engineers. As a software engineer you should rate a technology better based on its Engine and Non-functional Quality Attributes (Good Documentation is important but not the first and only thing to look at).

Laravel Eloquent implements Active Record pattern which makes data access slow for larger applications.

Collapse
adnanbabakan profile image
Adnan Babakan (he/him) Author

Hi
Thanks for your comment
I will try better next time I compare things
Thanks for the suggestion

Collapse
gabrieldevops profile image
gabo

Excelente enfoque visto desde el programador, pero no así desde el consumidor, el que va pagar por nuestros desarrollos, prefiero Phalcon por la RAPIDEZ de los sitios eso se traduce en $$. y lo explico:
MacDonalds el factor diferenciador que lo llevo al exito fue sabor y RAPIDEZ hacia el consumidor.
Domino´s Pizza el factor diferenciador que lo llevo al éxito fue RAPIDEZ hacia el consumidor.
Facebook es RAPIDO y en tiempo Real.
Whatsapp RAPIDO y en tiempo Real.
El usuario o consumidor antes que cualquier otra característica busca RAPIDEZ, TIEMPO REAL, incluso pasa con tu novia, que pasa cuando la esperas?? Laravel es la novia que se tarda en salir, si muy bonita, se puso su maquillaje(todas las cuestiones que acabas de explicar, despliegue, Middleware, etc) al final la novia se tardo.
Cuando desarrollamos pensamos siempre como programadores, o en función de nuestra capacidad, pero raramente pensamos como USUARIOS, como la GENTE QUE CONSUME en nuestros SITIOS, POR ESO ES IMPORTANTE la gente de Marketing. por eso PREFIERO PHALCON,

Collapse
fakharak profile image
Fakhar Anwar

FYI. Laravel architecture is monolithic, resource-hungry and does not scale well, while Phalcon has a reasonably good documentation and can be fused with Swoole PHP (Asynchrnous PHP Extension that allows its own HTTP server). If you like you can use parts of Laravel with Phalcon (if you are easy with Laravel, and want speed in some parts)

Selling Laravel only because it has more documentation material is not wisdom that one should expect from Software Engineers. As a software engineer you should rate a technology better based on its Engine and Non-functional Quality Attributes (Good Documentation is important but not the first and only thing to look at).

Laravel Eloquent implements Active Record pattern which makes data access slow for larger applications.

Collapse
eduluz1976 profile image
Eduardo Luz

Great work. Thanks for your post.
The only point I believe could give one more point to Phalcon, is on "deployment". Using Phalcon in Docker containers, is pretty easy to deploy to production. What do you think?

Collapse
adnanbabakan profile image
Adnan Babakan (he/him) Author

Hi
Yes for sure using Docker would be easy. But anyhow that is still some extra work to be done and it is not possible on shared hostings I believe.

Collapse
eduluz1976 profile image
Eduardo Luz

You are right. On shared hosting it is hard to do. Personally, I didn't find any Service Provider that supports Phalcon.

Thread Thread
adnanbabakan profile image
Adnan Babakan (he/him) Author

Believe me it kinda impossible to find one. LOL

Thread Thread
cleverhosting profile image
Norbert

I am hoster and i do.

phalcon 3.4 with php 5.6 and php 7.2
and

phalcon 4 with php 7.4

if you need shared hosting with phalcon i can help

Collapse
genievn profile image
Thanh Nguyen

Great article, thanks for sharing!

I found Phalcon much more enjoyable to work with, may I translate your article and give credit link?

Thanks & Br,
Thanh

Collapse
adnanbabakan profile image
Adnan Babakan (he/him) Author

Hi
I am glad you enjoyed the article. And yes of course you can translate it. What language though?

Collapse
genievn profile image
Thanh Nguyen

Thanks a lot, I will do Vietnamese translation on my personal blog, will update the link when I complete. Very few people knows about Phalcon, Laravel is king here :)

Thread Thread
adnanbabakan profile image
Adnan Babakan (he/him) Author

Thanks for your effort. Iran is also a country in which not many people know about Phalcon.

Thread Thread
genievn profile image
Thanh Nguyen

Long article, and I finished Vietnamese translation :)
Thanks again and I am waiting to read your next post

web68.vn/vi/p/so-sanh-laravel-va-p...

Collapse
parsaakbari80808080 profile image
Parsa Paris

Well done!

Collapse
adizbek1998 profile image
Adizbek Ergashev

Good comparison, thanks.

Collapse
chaosticsystem profile image
Sabin Chhetri

I think this article is incomplete. In regard to Restful API, you didn't talk about Phalcon Micro Application, which is very very easy to implement

Also you didn't consider the point running Phalcon and Laravel application in Command Line environment. I don't know about Laravel, but Phalcon has CLI utility to run its application easily in Command Line.