A full-stack PHP framework delivered as a C-extension

Its innovative architecture makes Phalcon the fastest PHP framework ever built!

Developers do not need to know C to use Phalcon. Its functionality is exposed as PHP classes and interfaces under the Phalcon namespace, ready to be used.
Features
  • Low overhead
  • ORM
  • PHQL
  • Transactions
  • Cache
  • Views & frontend
  • Template Engines
  • Template Engine (Volt)
  • i18n
  • Forms Builder
  • Flash messages

  • Low overhead
    Low memory consumption and CPU compared to traditional frameworks
  • MVC & HMVC
    Modules, components, models, views and controllers
  • Dependency Injection
    Dependency Injection and Location of services and it's itself a container for them.
  • Rest
    In this case, you can use either a micro or full stack application to meet your goal. In addition, a powerful set of HTTP helpers.
  • Autoloader
    Provides the autoloading mechanism of PHP classes following PSR-4.
  • Router
    Phalcon\Mvc\Router provides advanced routing capabilities.
Low overhead
PHP C-extension (Phalcon)
  • Zephir/C extensions are loaded together with PHP one time on the web server's daemon start process
  • Classes and functions provided by the extension are ready to use for any application
  • The code is compiled and isn't interpreted because it's already compiled to a specific platform and processor
  • Thanks to its low-level architecture and optimizations Phalcon provides the lowest overhead for MVC-based applications
MVC
Build single and multi-module applications with ease and pleasure. Using the file structure, scheme and patterns you already know.
                        
single/
    app/
        controllers/
        models/
        views/
    public/
        css/
        img/
        js/

                        
                    
                        
multiple/
     apps/
       frontend/
          controllers/
          models/
          views/
          Module.php
       backend/
          controllers/
          models/
          views/
          Module.php
       public/
       ../
                        
                    
Dependency Injection
Phalcon is built upon a powerful yet easy to understand and use pattern called Dependency Injection. Initialize or define services once - and use them virtually anywhere throughout the application.
                        
// Create the Dependency Injector Container
$di = new Phalcon\DI();

// Register classes, functions, components
$di->set("request", new Phalcon\Http\Request());

..

// Use anywhere else in code
$request = $di->getShared('request');
                        
                    
Restful Services
Writing REST servers and applications has never been easier. No boilerplate. Simple services will fit in one file.
                        
use Phalcon\Mvc\Micro;

$app = new Micro();

// Returning data in JSON
$app->get(
    '/check/status',
    function () {
        return $this
            ->response
            ->setJsonContent(
                [
                    'status' => 'important',
                ]
            )
        ;
    }
);

$app->handle();
                        
                    
Autoloader
Register namespaces, prefixes, directories or classes. Take advantage of the autoloader events and maintain full control over what files are loaded and from where.
                        
use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some namespaces
$loader->registerNamespaces(
    [
       'Example\Base'    => 'vendor/example/base/',
       'Example\Adapter' => 'vendor/example/adapter/',
       'Example'         => 'vendor/example/',
    ]
);

// Register autoloader
$loader->register();
                        
                    
Router
Routing as it supposed to be. Nothing more. Nothing less.
                        
// Create the router
$router = new \Phalcon\Mvc\Router();

// Define a route
$router->add(
   '/admin/users/my-profile',
   [
       'controller' => 'users',
       'action'     => 'profile',
   ]
);
                        
                    
  • ORM
    Object Relational Mapping
  • PHQL
    The powerful and secure Phalcon Query Language, PHQL
  • Transactions
    Transactions in Phalcon allows to keep the data integrity safe.
  • Cache
    Improve your performance with many of the backend caches that Phalcon provides
ORM
A powerful ORM is provided by Phalcon allowing you to manipulate database records as classes and objects. MySQL, PostgreSQL and SQLite are supported out of the box.
                        
use Invoices;
use Phalcon\Mvc\Model;

class Customers extends Model
{
    public $cst_id;

    public $cst_name;

    public function initialize()
    {
        $this->hasMany(
            'cst_id',
            Invoices::class,
            'inv_cst_id'
        );
    }
}
                        
                    
PHQL
PHQL is a high-level, object-oriented SQL dialect that allows to write queries using a standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. To achieve the highest performance possible, Phalcon provides a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
                        
$phql  = 'SELECT * '
       . 'FROM Formula\Cars '
       . 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);

$phql  = 'SELECT Formula\Cars.name '
       . 'FROM Formula\Cars '
       . 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);

$phql  = 'SELECT c.name '
       . 'FROM Formula\Cars c '
       . 'ORDER BY c.name';
$query = $manager->createQuery($phql);

$phql = 'SELECT c.* '
      . 'FROM Cars AS c '
      . 'ORDER BY c.name';
$cars = $manager->executeQuery($phql);

foreach ($cars as $car) {
    echo "Name: ", $car->name, "\n";
}
                        
                    
Transactions
When a process performs multiple database operations, it might be important that each step is completed successfully so that data integrity can be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data is committed to the database.
                        
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;

try {

    // Create a transaction manager
    $manager = new Manager();

    // Request a transaction
    $transaction = $manager->get();

    // Get the robots to be deleted
    $invoices = Invoices::find(
        'inv_cst_id = 123'
    );

    foreach ($invoices as $invoice) {
        $invoice->setTransaction($transaction);
        if ($invoice->delete() == false) {
            // Something is wrong - rollback transaction
            foreach ($invoice->getMessages() as $message) {
                $transaction
                    ->rollback($message->getMessage());
            }
        }
    }

    // Everything is OK - commit transaction
    $transaction->commit();

    echo "Robots were deleted successfully!";

} catch (Failed $e) {
    echo "Failed, reason:  ", $e->getMessage();
}
                        
                    
Cache
The cache component allows faster access to frequently used or already processed data. It supports many backends such as Redis, Memcached, Mongo, Files, Apc and more
                        
use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\Serializer\SerializerFactory;

$serializerFactory = new SerializerFactory();
$adapterFactory    = new AdapterFactory($serializerFactory);

$options = [
    'defaultSerializer' => 'Json',
    'lifetime'          => 7200
];

$adapter = $adapterFactory
    ->newInstance('apcu', $options);

$cache = new Cache($adapter);
                        
                    
  • Template Engines
    Views represent the user interface of your application
  • Template Engine (Volt)
    A template engine inspired by Jinja but built in C for PHP
  • i18n
    Translate your applications to many languages easily
  • Forms Builder
    Easily create HTML forms
  • Flash messages
    Flash messages are used to notify the user about the state of actions.
Template Engines
Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
                        
<html>
    <body>
    <div class='top'>
        <?php $this->partial('shared/ad_banner'); ?>
    </div>
    <div class='content'>
        <h1>Robots</h1>
        <p>
            Check out our specials for robots:
        </p>
        ...
    </div>
    <div class='footer'>
        <?php $this->partial('shared/footer'); ?>
    </div>
    </body>
</html>
                        
                    
Template Engine (Volt)
Volt is an ultra-fast and designer friendly templating language written in Zephir/C for PHP. It provides you a set of helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, just as you can use it as a stand-alone component in your applications.
                        
{# app/views/products/show.volt #}
{% block last_products %}
{% for prod in products %}
    * Name: {{ prod.name|e }}
    {% if prod.status == 'Active' %}
       Price: {{ prod.price + prod.taxes/100}}
    {% endif  %}
{% endfor  %}
{% endblock %}
                        
                    
i18n
The component Phalcon\Translate aids in creating multilingual applications. Applications using this component, display content in different languages, based on the user's chosen language supported by the application.
// app/messages/en.php
$messages = [
    'hi'      => 'Hello',
    'bye'     => 'Good Bye',
    'hi-name' => 'Hello %name%',
    'song'    => 'This song is %song%'
];

// app/messages/es.php
$messages = [
    'hi'      => 'Hola',
    'bye'     => 'Adiós',
    'hi-name' => 'Hola %name%',
    'song'    => 'Esta canción es %song%'
];

use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;

// UserController.php
class UserController extends Controller
{
    protected function getTranslation()
    {
        // Browser's best language
        $language = $this
            ->request
            ->getBestLanguage();

        // Check the lang translation file
        $fileName = 'app/messages/'
                  . $language
                  . '.php';
        if (file_exists($fileName) {
            require $fileName;
        } else {
            // Fallback to some default
            require 'app/messages/en.php';
        }

        // Return a translation object
        return new NativeArray(
            array(
                'content' => $messages
            )
        );
    }

    public function indexAction()
    {
        $this->view->name = 'Mike';

        $this->view->t = $this
            ->getTranslation();
    }
}
// user.volt
<p><?php echo $t->_('hi'), ' ', $name; ?></p>
                        
                    
Forms Builder
Each element in the form can be rendered as required by the developer. Internally, Phalcon\Tag is used to produce the correct HTML for each element and you can pass additional HTML attributes as the second parameter of render():
                        
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;

$form = new Form();

$form->add(new Text('name'));

$form->add(new Text('telephone'));

$form->add(
    new Select(
        'telephoneType',
        array(
            'H' => 'Home',
            'C' => 'Cellphone'
        )
    )
);
                        
                    
Flash messages
Use the flash notifier to show notifications to a user in a web application:
                        
use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function saveAction()
    {
        $this->flash->error(
            'there were errors in this form'
        );
        $this->flash->success(
            'yes!, everything is fine'
        );
        $this->flash->notice(
            'this is a notice for users'
        );
        $this->flash->warning(
            'this is just a warning'
        );
    }
}
                        
                    
  • ACL
    Access Control List allows users to access the modules they're authorized to
  • Sharding
    Connect, store and retrieve data from many database systems at the same time
  • Crypt
    Encrypt/Decrypt important data to keep them safe from unauthorized third-parties
  • Events
    Extend the most of the framework components by setting 'hook points'. Create your own events and make your application more flexible and powerful
ACL
This is how you can built the access control list (ACL):
                        
use Phalcon\Acl;
use Phalcon\Acl\Enum;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory;

// Create the ACL
$acl = new Memory();

// The default action is DENY access
$acl->setDefaultAction(Enum::DENY);

// Register two roles, Users
// and Guests
$roles = array(
    'users'  => new Role('Users'),
    'guests' => new Role('Guests')
);

foreach ($roles as $role) {
    $acl->addRole($role);
}
                        
                    
Sharding
Attach models to different databases
                        
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Db\Adapter\Pdo\PostgreSQL;

// This service returns a MySQL database
$container->set(
    'dbMysql',
    function () {
        return new Mysql(
            [
                'host'     => 'localhost',
                'username' => 'root',
                'password' => 'secret',
                'dbname'   => 'tutorial',
            ]
        );
    }
);

// This service returns a PostgreSQL database
$container->set(
    'dbPostgres',
    function () {
        return new PostgreSQL(
            [
                'host'     => 'localhost',
                'username' => 'postgres',
                'password' => '',
                'dbname'   => 'invo',
            ]
        );
    }
);
                        
                    
Encryption
Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the openssl PHP's encryption library.
                        
use Phalcon\Crypt;

$crypt = new Crypt();

$key  = 'This is a secret key (32 bytes).';
$text = 'The text you want to encrypt.';

$encrypted = $crypt->encrypt($text, $key);

echo $crypt->decrypt($encrypted, $key);
                        
                    
Events Management
An EventsManager allows us to attach listeners to a particular type of event. The type that interests us now is 'dispatch'. The following code filters all events produced by the Dispatcher:
                        
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager;

$container->set(
    'dispatcher',
    function () {
        // Create an events manager
        $manager = new Manager();

        // Listen for events produced in the
        // dispatcher using the SecurityPlugin
        $manager->attach(
            'dispatch:beforeExecuteRoute',
            new SecurityPlugin
        );

        // Handle exceptions and not-found
        // exceptions using NotFoundPlugin
        $manager->attach(
            'dispatch:beforeException',
            new NotFoundPlugin
        );

        $dispatcher = new Dispatcher();

        // Assign the events manager
        // to the dispatcher
        $dispatcher
            ->setEventsManager($manager);

        return $dispatcher;
    }
);
                        
                    
A polling app built from scratch in < 15 min
Watch the demo video
Come join our vibrant developer community!
Community contributions in Extensions, Plugins, Adapters, VM, examples, source code... and more
Phalcon contributors
Phalcon is improved everyday by our amazing community
Contribute