Google News
logo
Phalcon Interview Questions
Phalcon is an open source full stack framework for PHP, written as a C-extension. Phalcon is optimized for high performance. Its unique architecture allows the framework to always be memory resident, offering its functionality whenever it’s needed, without expensive file stats and file reads that traditional PHP frameworks employ.
Phalcon Framework features are :
* Low overhead
* MVC & HMVC Pattern
* Dependency Injection
* Support for Rest
* Autoloader
* Router
Phalcon Framework directory structure are given below:
* App
Config
Controllers
Library
Migrations
Models
Views
* Cache
* Public
Css
files
img
js
temp
* .htaccess
* .htaccess
* .htrouter.php
* index.html
A pull request for Phalcon must be against our main repository cphalcon. It is a collection of changes to the code that:
 
* fix a bug (current issue)

* introduce new functionality or enhancement.


Your pull request must include :
 
* Target the correct branch.

* Update the relevant CHANGELOG.md

* Contain unit tests

* Updates to the documentation and usage examples as necessary

* Your code must abide by the coding standards that Phalcon uses. For PHP code we use PSR-2 while for Zephir code, we have an .editorconfig file available at the root of the repository to help you follow the standards.

NOTE : We do not accept Pull Requests to the master branch


If your pull request relates to fixing an issue/bug, please link the issue number in the pull request body. You can utilize the template we have in GitHub to present this information. If no issue exists, please create one.
 
For new functionality, we will need to have an issue created and referenced. If the functionality you are introducing collides with the philosophy and implementation of Phalcon, the pull request will be rejected.
 
Additionally any new functionality that introduces breaking changes will not be accepted for the current release but instead will need to be updated to target the next major version.
 
It is highly recommended to discuss your NFR and PR with the core team and most importantly with the community so as to get feedback, guidance and to work on a release plan that will benefit everyone.

Branch and Commits : The following steps are recommended but not mandatory.
 
If you are working on an issue, note the number of the issue down. Let us assume that the issue is:
 
#12345 - Create New Object
 
* Checkout the 4.0.x branch
* Create a branch : T12345-create-new-object

The name of the branch starts with T, followed by the number of the issue and then the title of the issue as a slug.
 
In your cphalcon folder navigate to .git/hooks
 
Create a new file called commit-msg and paste the code below in it and save it :
#!/bin/bash
# This Way You can Customize Which Branches Should be Skipped When
# Prepending Commit Message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
  BRANCHES_TO_SKIP=(master develop)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
  ISSUE="$(echo $BRANCH_NAME | cut -d'-' -f 1)"
  ISSUE="${ISSUE/T/#}"
  sed -i.bak -e "1s/^/[$ISSUE] - /" $1
fi
 
Ensure that the file is executable
chmod a+x commit-msg
Any commits you add now to your branch will appear tied to the 12345 issue.
 
Doing the above allows everyone to see which commits relate to which issue.
List of NFRs : 
 
A NFR is a short document explaining how a new feature request must be submitted, how it can be implemented, and how it can help core developers and others to understand and implement it.
 
A NFR contains :
 
* Suggested syntax
* Suggested class names and methods
* A description detailing the usage
* How it can benefit the framework and the community
* If the feature is already implemented in other frameworks, a short explanation of how that was implemented and its advantages
Phalcon is compiled into a C extension loaded on your web server. Because of that, bugs lead to segmentation faults, causing Phalcon to crash some of your web server processes.
 
For debugging these segmentation faults a stacktrace is required. Creating a stack trace requires a special build of php and some steps need to be done to generate a trace that allows the Phalcon team to debug this behavior.
 
Please follow this guide to understand how to generate the backtrace.
 
 
The Devilbox is a modern and highly customizable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts, SSL certificates and DNS records are created automatically. Reverse proxies per project are supported to ensure listening server such as NodeJS can also be reached. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is already pre-setup.
 
Furthermore, the Devilbox provides an identical and reproducible development environment for different host operating systems.
 
This example will use phalcon to install Phalcon from within the Devilbox PHP container. After completing the steps listed below, you will have a working Phalcon setup ready to be served via http and https.
 
Configuration
The following configuration will be used :

Project name my-phalcon
VirtualHost directory /shared/httpd/my-phalcon
Database n.a.
TLD_SUFFIX loc
Project URL http://my-phalcon.loc, https://my-phalcon.loc
Nanobox is a portable, micro platform for developing and deploying apps. When working locally, Nanobox uses Docker to spin up and configure a virtual development environment configured to your specific needs. When you’re ready to deploy to live servers, Nanobox will take that same environment and spin it up on your cloud provider of choice, where you can then manage and scale your app through the Nanobox dashboard.
 
Create a New Project : Create a project folder and cd into it :
mkdir nanobox-phalcon && cd nanobox-phalcon
In Phalcon, database related functions are:
* find()
* findFirst()
* query()
* findFirstBy etc.
Phalcon supported PDO_ database engines that are :

Phalcon\Db\Adapter\Pdo\Mysql : Mysql
Phalcon\Db\Adapter\Pdo\Postgresql : Postgresql
Phalcon\Db\Adapter\Pdo\Sqlite : Sqlite
Zephir stands for Ze(nd Engine) Ph(p) I(nt)r(mediate) . It is a high level language. It is used for creation and maintainability of extensions for PHP. It exported to C code that can be compiled and optimized by major C compilers such as gcc/clang/vc++.
In Phalcon, there are various tyes of application event :

Event Name Triggered
boot Executed when the application handles its first request
beforeStartModule Before initialize a module, only when modules are registered
afterStartModule After initialize a module, only when modules are registered
beforeHandleRequest Before execute the dispatch loop
afterHandleRequest After execute the dispatch loop

In Phalcon, we can pass data from controller to view by setVar() method.
$this->view->setVar("username", $user->username);
Phalcon\Loader is an autoloader that implements PSR-4. Just like any autoloader, depending on its setup, it will try and find the files your code is looking for based on file, class, namespace etc. Since this component is written in C, it offers the lowest overhead when processing its setup, thus offering a performance boost.
 
This component relies on PHP’s autoloading classes capability. If a class defined in the code has not been included yet, a special handler will try to load it. Phalcon\Loader serves as the special handler for this operation. By loading classes on a need to load basis, the overall performance is increased since the only file reads that occur are for the files needed. This technique is called lazy initialization.
 
The component offers options for loading files based on their class, file name, directories on your file system as well as file extensions.
 
Registration : Usually we would use the spl_autoload_register() to register a custom autoloader for our application. Phalcon\Loader hides this complexity. After you define all your namespaces, classes, directories and files you will need to call the register() function, and the autoloader is ready to be used.
<?php

use Phalcon\Loader;

$loader = new Loader();

$loader->registerNamespaces(
    [
       'MyApp'        => 'app/library',
       'MyApp\Models' => 'app/models',
    ]
);

$loader->register();
register() uses spl_autoload_register() internally. As a result it accepts also accepts the boolean prepend parameter. If supplied and is true, the autoloader will be prepended on the autoload queue instead of appended (default behavior).
 
You can always call the isRegistered() method to check if your autoloader is registered or not.
In Loader if a class is added according to its need in program, performance is increased as only specific file is included. This technique is known as lazy initialization.
* Registering Namespaces
* Registering Directories
* Registering Classes
* Registering Files
It is provided by logging services for application. We can login to different backend using different adapters. It offers transaction logging, configuration options, different formats and filters.
These tools help you to generate skeleton code, maintain your database structure and helps to speedup development. Core components of your application can be generated with a simple command, allowing you to easily develop applications using Phalcon.
 
Phalcon Devtool can be controlled using the cmd line or the web interface.
 
Installation : Phalcon Devtools can be installed using composer. Make sure you have installed first.
 
Install Phalcon Devtools globally
composer global require phalcon/devtools
Or only inside your project
composer require phalcon/devtools
Test your installation by typing : phalcon
$ phalcon

Phalcon DevTools (4.0.0)

Available commands:
  info             (alias of: i)
  commands         (alias of: list, enumerate)
  controller       (alias of: create-controller)
  module           (alias of: create-module)
  model            (alias of: create-model)
  all-models       (alias of: create-all-models)
  project          (alias of: create-project)
  scaffold         (alias of: create-scaffold)
  migration        (alias of: create-migration)
  webtools         (alias of: create-webtools)
  serve            (alias of: server)
  console          (alias of: shell, psysh)
PHQL (Phalcon Query Language) allows user to implement query language similar to SQL query language. PHQL is implemented as a parser which connects to RDBMS.
* It secures the code using bound parameters.
* It prevents injection by executing one SQL statement per call.
* It ignores all comments which mostly used in SQL injections.
* It only allows data manipulation statement to execute.
Endpoint Description
/login Path /session/login. Presents the login screen
/logout Path /session/logout. Logs user out, redirects to /login
/portal/invoices/list List invoices for the currently logged in customer
/portal/invoices/view/{0-9} View invoice for the currently logged in customer
/portal/invoices/pay/{0-9} Pay invoice (payment gateway)
/portal/reports/list List available reports for the logged in customer
/portal/reports/view/{0-9} View report for this customer
/accounting/invoices/add Add new invoice
/accounting/invoices/edit/{0-9} Edit an invoice
/accounting/invoices/view/{0-9} View an invoice
/accounting/invoices/list List all invoices
/accounting/invoices/void/{0-9} Void an invoice
/admin/cache/view View all cache items
/admin/cache/delete/{0-9} Delete a cache item
/admin/cache/void Void the whole cache
/admin/permissions/list Show the current permissions
/admin/permissions/add Add a new permission
/admin/permissions/edit/{0-9} Edit a permission
/admin/products/list List all products
/admin/products/add Add a product
/admin/products/edit/{0-9} Edit a product
/admin/products/delete/{0-9} Delete a product
/admin/products/view/{0-9} View a product
/admin/users/list List all users
/admin/users/add Add a user
/admin/users/edit/{0-9} Edit a user
/admin/users/delete/{0-9} Delete a user
/admin/users/view/{0-9} View a user
Phalcon\Di is a container that stores services or components (classes). These services are available throughout the application and ease development. Let us assume we are developing a component called InvoiceComponent that performs some calculations for a customer’s invoice. It requires a database connection to retrieve the Invoice record from the database.
 
Our component can be implemented as follows :
<?php

use Phalcon\Db\Adapter\Mysql;

class InvoiceComponent
{
    public function calculate()
    {
        $connection = new Mysql(
            [
                'host'     => 'localhost',
                'username' => 'root',
                'password' => 'secret',
                'dbname'   => 'tutorial',
            ]
        );
        
        $invoice = $connection->exec(
            'SELECT * FROM Invoices WHERE inv_id = 1'
        );

        // ...
    }
}

$invoice = new InvoiceComponent();
$invoice->calculate();
We use the calculate method to get our data. Inside the method, we create a new database connection to MySQL with set credentials and after that we execute a query. Although this is a perfectly valid implementation, it is impractical and will hinder the maintenance of our application later on, due to the fact that our connection parameters or type of the database are hard coded in the component.
CLI stands for Command Line Interface. CLI applications are executed from the command line or a shell prompt. One of the benefits of CLI applications is that they do not have a view layer (only potentially echoing output on screen) and can be run more than one at a time. Some of the common usages are cron job tasks, manipulation scripts, import data scripts, command utilities and more.
 
Structure : You can create a CLI application in Phalcon, using the Phalcon\Cli\Console class. This class extends from the main abstract application class, and uses a directory in which the Task scripts are located. Task scripts are classes that extend Phalcon\Cli\Task and contain the code that we need executed.
 
The directory structure of a CLI application can look like this :
src/tasks/MainTask.php
php cli.php
In the above example, the cli.php is the entry point of our application, while the src/tasks directory contains all the task classes that handle each command.
The Phalcon\Cache namespace offers a Cache component, that implements the PSR-16 interface, making it compatible with any component that requires that interface for its cache.
 
Frequently used data or already processed/calculated data, can be stored in a cache storage for easier and faster retrieval. Since Phalcon\Cache components are written in Zephir, and therefore compiled as C code, they can achieve higher performance, while reducing the overhead that comes with getting data from any storage container. Some examples that warrant the use of cache are :
 
* You are making complex calculations and the output does not change frequently
* You are producing HTML using the same data all the time (same HTML)
* You are accessing database data constantly which does not change often.
 
Phalcon\Cache components rely on Phalcon\Storage components. Phalcon\Storage is split into two categories : Serializers and Adapters.
 
Cache : In order to instantiate a new Phalcon\Cache component, you will need to pass a Phalcon\Cache\Adapter\* class in it or one that implements the Phalcon\Cache\Adapter\AdapterInterface. For a detailed explanation on adapters and serializers, see below.
<?php

use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\SerializerFactory;

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

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

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

$cache = new Cache($adapter);
Websites and web applications are vulnerable to XSS attacks and although PHP provides escaping functionality, in some contexts it is not sufficient/appropriate. Phalcon\Escaper provides contextual escaping and is written in Zephir, providing the minimal overhead when escaping different kinds of texts.
 
We designed this component based on the XSS (Cross Site Scripting) Prevention Cheat Sheet created by the OWASP. Additionally, this component relies on mbstring to support almost any charset. To illustrate how this component works and why it is important, consider the following example :
<?php

use Phalcon\Escaper;

$escaper = new Escaper();

$title = '</title><script>alert(1)</script>';
echo $escaper->escapeHtml($title);
// &lt;/title&gt;&lt;script&gt;alert(1)&lt;/script&gt;

$css = ';`(';
echo $escaper->escapeCss($css);
// &#x3c &#x2f style&#x3e

$fontName = 'Verdana\"</style>';
echo $escaper->escapeCss($fontName);
// Verdana\22 \3c \2f style\3e

$js = "';</script>Hello";
echo $escaper->escapeJs($js);
// \x27\x3b\x3c\2fscript\x3eHello
Phalcon\Logger is a component providing logging services for applications. It offers logging to different back-ends using different adapters. It also offers transaction logging, configuration options and different logging formats. You can use the Phalcon\Logger for any logging need your application has, from debugging processes to tracing application flow.
 
The Phalcon\Logger has been rewritten to comply with PSR-3. This allows you to use the Phalcon\Logger to any application that utilizes a PSR-3 logger, not just Phalcon based ones.
 
In v3, the logger was incorporating the adapter in the same component. So in essence when creating a logger object, the developer was creating an adapter (file, stream etc.) with logger functionality.
 
For v4, we rewrote the component to implement only the logging functionality and to accept one or more adapters that would be responsible for doing the work of logging. This immediately offers compatibility with PSR-3 and separates the responsibilities of the component. It also offers an easy way to attach more than one adapter to the logging component so that logging to multiple adapters can be achieved. By using this implementation we have reduced the code necessary for this component and removed the old Logger\Multiple component.
 
Adapters : This component makes use of adapters to store the logged messages. The use of adapters allows for a common logging interface which provides the ability to easily switch back-ends, or use multiple adapters if necessary. The adapters supported are :

Adapter Description
Phalcon\Logger\Adapter\Noop Blackhole adapter (used for testing mostly)
Phalcon\Logger\Adapter\Stream Logs messages on a file stream
Phalcon\Logger\Adapter\Syslog Logs messages to the Syslog
Behaviors are shared constructs that several models may adopt in order to re-use code. Although you can use traits to reuse code, behaviors have several benefits that make them more appealing. Traits require you to use exactly the same field names for common code to work. Behaviors are more flexible.
 
The ORM provides an API to implement behaviors in your models. Also, you can use the events and callbacks as seen before as an alternative to implement behaviors.
 
A behavior must be added in the model initializer, a model can have zero or more behaviors :
<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;

class Invoices extends Model
{
    /**
     * @var int
     */
    public $inv_id;

    /**
     * @var string
     */
    public $inv_created_at;

    /**
     * @var int
     */
    public $inv_status_flag;

    /**
     * @var string
     */
    public $inv_title;

    public function initialize()
    {
        $this->addBehavior(
            new Timestampable(
                [
                    'beforeCreate' => [
                        'field'  => 'inv_created_at',
                        'format' => 'Y-m-d',
                    ],
                ]
            )
        );
    }
}
Cookies stores small text files in browser. It is known as browser cookies.
 
Types of cookies are:
 
* Session Cookies
* Persistent Cookies
The Phalcon\Mvc\Router component allows you to define routes that are mapped to controllers or handlers that receive and can handle the request. The router has two modes: MVC mode and match-only mode. The first mode is ideal for working with MVC applications.
<?php

use Phalcon\Mvc\Router;

$router = new Router();

$router->add(
    '/admin/invoices/list',
    [
        'controller' => 'invoices',
        'action'     => 'list',
    ]
);

$router->handle(
    $_SERVER["REQUEST_URI"]
);
 
 
Constants : There are two constants available for the Phalcon\Mvc\Router component that are used to define the position of the route in the processing stack.
POSITION_FIRST
POSITION_LAST
Methods : 
public function __construct(
    bool $defaultRoutes = true
)
Phalcon\Mvc\Router constructor : 
public function add(
    string $pattern, 
    mixed $paths = null, 
    mixed $httpMethods = null, 
    mixed $position = Router::POSITION_LAST
): RouteInterface
Sessions are used in PHP to persist data between requests. This enables developers to build better applications and increase the user experience. A very common usage of sessions is to keep whether a user is logged in or not. Phalcon\Session\Manager is an object oriented approach to handle sessions using Phalcon. There are several reasons to use this component instead of raw sessions or accessing the $_SESSION superglobal: 
 
* You can easily isolate session data across applications on the same domain
* Intercept where session data is set/get in your application
* Change the session adapter according to the application needs
 
Manager :  Phalcon\Session\Manager is a component that allows you to manipulate sessions in your application. This manager accepts an adapter which is the way the data will be communicated to a particular store.
<?php

use Phalcon\Session\Manager;
use Phalcon\Session\Adapter\Stream;

$session = new Manager();
$files = new Stream(
    [
        'savePath' => '/tmp',
    ]
);
$session->setAdapter($files);
CSRF stands for Cross Site Request Forgery. CSRF is created to prevent the form values from being sent outside our application. It generates a random nonce (token) in each form.
Phalcon\Validation is an independent validation component that validates an arbitrary set of data. This component can be used to implement validation rules on data objects that do not belong to a model or collection.
 
The following example shows its basic usage :
<?php

use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;

$validation = new Validation();

$validation->add(
    'name',
    new PresenceOf(
        [
            'message' => 'The name is required',
        ]
    )
);

$validation->add(
    'email',
    new PresenceOf(
        [
            'message' => 'The e-mail is required',
        ]
    )
);

$validation->add(
    'email',
    new Email(
        [
            'message' => 'The e-mail is not valid',
        ]
    )
);

$messages = $validation->validate($_POST);

if (count($messages)) {
    foreach ($messages as $message) {
        echo $message, '<br>';
    }
}
The Phalcon\Mvc\Dispatcher is the component responsible for instantiating controllers and executing the required actions on them in an MVC application. Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.
<?php

use Phalcon\Di;
use Phalcon\Mvc\Dispatcher;

$container  = new Di();
$dispatcher = new Dispatcher();

$dispatcher->setDI($container);

$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);

$controller = $dispatcher->dispatch();
Phalcon\Http\Request is a component that encapsulates the actual HTTP request (usually originated by a browser) and sent to our application. The Phalcon\Http\Request object is a simple value object that is passed between the dispatcher and controller classes, wrapping the HTTP request environment. It also offers easy access to information such as header data, files, method, variables etc.
<?php

use Phalcon\Http\Request;

$request = new Request();

// POST
if (true === $request->isPost()) {
    // AJAX
    if (true === $request->isAjax()) {
        // ....
    }
}
Getting Values : PHP automatically fills the superglobal arrays $_GET, $_POST and $_REQUEST depending on the type of the request. These arrays contain the values present in forms submitted or the parameters sent via the URL. The variables in the arrays are never sanitized and can contain illegal characters or even malicious code, which can lead to SQL injection or Cross Site Scripting (XSS) attacks.
 
Phalcon\Http\Request allows you to access the values stored in the $_GET, $_POST and $_REQUEST arrays and sanitize or filter them with the filter service.
 
There are 5 methods that allow you to retrieve submitted data from a request :
 
* get()
* getQuery()
* getPost()
* getPut()
* getServer()

All (except getServer()) accept the following parameters :
 
* name the name of the value to get
* filters (array/string) the sanitizers to apply to the value
* defaultValue returned if the element is not defined (null)
* notAllowEmpty if set (default) and the value is empty, the defaultValue will be returned; otherwise null
* noRecursive applies the sanitizers recursively in the value (if value is an array)
<?php

use Phalcon\Http\Request;

$request = new Request();

$request->get(
    $name = null,            // string
    $filters = null,         // mixed
    $defaultValue = null,    // mixed
    $notAllowEmpty = false,  // bool
    $noRecursive = false     // bool
): mixed​
Phalcon\Http\Response is a component that encapsulates the actual HTTP response by the application to the user. The most commonly returned payload is headers and content. Note that this is not only the actual response payload. The component acts as a constructor of the response and as a HTTP client to send the response back to the caller. You can always use the Phalcon\Http\Message\Response for a PSR-7 compatible response and use a client such as Guzzle to send it back to the caller.
<?php

use Phalcon\Http\Response;

// Getting a response instance
$response = new Response();

$response->setStatusCode(404, 'Not Found');
$response->setContent("Sorry, the page doesn't exist");
$response->send();

 

The above example demonstrates how we can send a 404 page back to the user.
 
The component implements the Phalcon\Http\ResponseInterface, Phalcon\Di\InjectionAware and Phalcon\Events\EventsAware interfaces.
 
Upon instantiation, you can use the constructor to set your content, the code as well as the status if you need to.
<?php

use Phalcon\Http\Response;

// Getting a response instance
$response = new Response(
    "Sorry, the page doesn't exist",
    404, 
    'Not Found'
);

$response->send();
The Phalcon\Http\Response offers a collection to store and manipulate cookies. You can then send those cookies back with the response.
 
To set up cookies you will need to instantiate a Phalcon\Http\Response\Cookies object or any object that implements the Phalcon\Http\Response\CookiesInterface.
<?php

use Phalcon\Http\Response;
use Phalcon\Http\Response\Cookies;

$response = new Response();
$cookies  = new Cookies();

$response->setCookies($cookies);
To get the cookies set by the user you can use the getCookies() method on the Phalcon\Http\Response object. The method returns a Phalcon\Http\Response\Cookies collection object. You can set the cookies in the response object using the setCookies(), as shown above, and then use sendCookies() to send them back to the caller.
Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the openssl PHP’s encryption library.
 
By default, this component utilizes the AES-256-CFB cipher.
 
The cipher AES-256 is used among other places in SSL/TLS across the Internet. It’s considered among the top ciphers. In theory it’s not crackable since the combinations of keys are massive. Although NSA has categorized this in Suite B, they have also recommended using higher than 128-bit keys for encryption.
 
 
Basic Usage : This component is designed to be very simple to use :
<?php

use Phalcon\Crypt;

$key = "12345"; // Your luggage combination

$crypt     = new Crypt();
$text      = 'This is the text that you want to encrypt.';
$encrypted = $crypt->encrypt($text, $key);

echo $crypt->decrypt($encrypted, $key);
Phalcon\Security\JWT is a namespace that contains components that allow you to issue, parse and validate JSON Web Tokens as described in RFC 7519. These components are:
 
An example of using the component is :
<?php

use Phalcon\Security\JWT\Builder;
use Phalcon\Security\JWT\Signer\Hmac;
use Phalcon\Security\JWT\Token\Parser;
use Phalcon\Security\JWT\Validator;

// Defaults to 'sha512'
$signer  = new Hmac();

// Builder object
$builder = new Builder($signer);

$now        = new DateTimeImmutable();
$issued     = $now->getTimestamp();
$notBefore  = $now->modify('-1 minute')->getTimestamp();
$expires    = $now->modify('+1 day')->getTimestamp();
$passphrase = 'QcMpZ&b&mo3TPsPk668J6QH8JA$&U&m2';

// Setup
$builder
    ->setAudience('https://target.phalcon.io')  // aud
    ->setContentType('application/json')        // cty - header
    ->setExpirationTime($expires)               // exp 
    ->setId('abcd123456789')                    // JTI id 
    ->setIssuedAt($issued)                      // iat 
    ->setIssuer('https://phalcon.io')           // iss 
    ->setNotBefore($notBefore)                  // nbf
    ->setSubject('my subject for this claim')   // sub
    ->setPassphrase($passphrase)                // password 
;

// Phalcon\Security\JWT\Token\Token object
$tokenObject = $builder->getToken();

// The token
echo $tokenObject->getToken();

// Token split into different lines for readability
//
// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImN0eSI6ImFwcGxpY2F0aW9uXC9qc29uIn0.
// eyJhdWQiOlsiaHR0cHM6XC9cL3RhcmdldC5waGFsY29uLmlvIl0sImV4cCI6MTYxNDE4NTkxN
// ywianRpIjoiYWJjZDEyMzQ1Njc4OSIsImlhdCI6MTYxNDA5OTUxNywiaXNzIjoiaHR0cHM6XC
// 9cL3BoYWxjb24uaW8iLCJuYmYiOjE2MTQwOTk0NTcsInN1YiI6Im15IHN1YmplY3QgZm9yIHR
// oaXMgY2xhaW0ifQ.
// LdYevRZaQDZ2lul4CCQ5DymeP2ubcapTtgeezOZGIq7Meu7rFF1pv32b-AMWOxCS63CQz_jpm
// BPlPyOeEAkMbg
// $tokenReceived is what we received
$tokenReceived = getMyTokenFromTheApplication();
$audience      = 'https://target.phalcon.io';
$now           = new DateTimeImmutable();
$issued        = $now->getTimestamp();
$notBefore     = $now->modify('-1 minute')->getTimestamp();
$expires       = $now->getTimestamp();
$id            = 'abcd123456789';
$issuer        = 'https://phalcon.io';

// Defaults to 'sha512'
$signer     = new Hmac();
$passphrase = 'QcMpZ&b&mo3TPsPk668J6QH8JA$&U&m2';

// Parse the token
$parser      = new Parser();

// Phalcon\Security\JWT\Token\Token object
$tokenObject = $parser->parse($tokenReceived);

// Phalcon\Security\JWT\Validator object
$validator = new Validator($tokenObject, 100); // allow for a time shift of 100

// Throw exceptions if those do not validate
$validator
    ->validateAudience($audience)
    ->validateExpiration($expires)
    ->validateId($id)
    ->validateIssuedAt($issued)
    ->validateIssuer($issuer)
    ->validateNotBefore($notBefore)
    ->validateSignature($signer, $passphrase)
;
 
The above example gives a general view on how the component can be used to generate, parse and validate JSON Web Tokens.
In Phalcon, we can read, write and delete sessions by using following code:
Creating session: $this->session->set("user-name", "Ramana");

Reading or Retriving session: $this->session->get("user-name");

Deleting or Removing session: $this->session->remove("user-name");
There are various differences between Phalcon and other framework :
Framework Yii Laravel Phalcon
Type of Project It helps to creating large projects It is used to create Web application. It is used to design variety of projects.
Database support It supports relational and non relational db It supports relational DB. It supports both relational and non relational db
Language It is purely written in PHP It is written in PHP and follow MVC pattern. It is written in PHP and C language.
Scalability It is quit scalable. Scalability is high Good for medium projects.
Performance Comparatively low High but less in compare to Phalcon High Performance
There are following features of a controller.

* It helps to update the model's state by sending command to the model.
* It is also used to send command to the associated view.
* It acts as an intermediary between the model and the view.
There are various differences between .volt and .phtml that are given below in table :

.volt .phtml
It is used when the template engine set up. It is used when the template engine is PHP itself.
It can be used as a stand-alone component. It cannot be used as a stand-alone component.
Volt views are compiled to PHP code. It includes PHP volt so there is no need of compilation in Phalcon framework.
There are various different type of HTTP methods :

GET : It is used to retrieve and search data.
POST : It is used to add data.
PUT : It is used to update data.
DELETE : It is used to delete data.
Phalcon\Http\Message\Request is an implementation of the PSR-7 HTTP messaging interface as defined by PHP-FIG.
 
This implementation has been created to establish a standard between middleware implementations. Applications often need to send requests to external endpoints. To achieve this you can use the Phalcon\Http\Message\Request object. In return, our application will receive back a response object.
 
NOTE : Phalcon does not restrict you in using a specific HTTP Client. Any PSR-7 compliant client will work with this component so that you can perform your requests.
 
NOTE : In the examples below, $httpClient is the client of your choice which implements PSR-7.
<?php

use Phalcon\Http\Message\Request;
use Phalcon\Http\Message\Uri;

$request = new Request();
$uri     = new Uri('https://api.phalcon.io/companies/1');

$jwtToken = 'abc.def.ghi';

$request = $request
   ->withMethod('POST')
   ->withHeader('Authorization', 'Bearer ' . $jwtToken)
   ->withHeader('Content-Type', 'application/json')
;

$result = $httpClient->send($request);
 
We are creating a new Phalcon\Http\Message\Request object and a new Phalcon\Http\Message\Uri object with the target URL. Following that we define the method (POST) and additional headers that we need to send with our request. The client then sends the request by using the request object.
 
The above example can be implemented by only using the constructor parameters :
<?php

use Phalcon\Http\Message\Request;

$jwtToken = 'abc.def.ghi';

$request = new Request(
    'POST',
    'https://api.phalcon.io/companies/1',
    'php://memory',
    [
        'Authorization' => 'Bearer ' . $jwtToken,
        'Content-Type'  => 'application/json',
    ]
);

$result = $httpClient->send($request);
The Request object created is immutable, meaning it will never change. Any call to methods prefixed with with* will return a clone of the object to maintain immutability, as per the standard.
Phalcon is written in C as an extension for PHP. There is a PECL extension that offers internationalization functions to PHP applications called intl. Its documentation can be found in the pages of the official PHP manual.
 
Phalcon does not offer this functionality, since creating such a component would be replicating existing code.
 
In the examples below, we will show you how to implement the intl extension’s functionality into Phalcon powered applications.
<?php

use Locale;

$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

// Locale could be something like 'en_GB' or 'en'
echo $locale;

Below method returns a locale identified. It is used to get language, culture, or regionally-specific behavior from the Locale API.
 
Examples of identifiers include :
 
* en-US (English, United States)
* ru-RU (Russian, Russia)
* zh-Hant-TW (Chinese, Traditional Script, Taiwan)
* fr-CA, fr-FR (French for Canada and France respectively)
The component Phalcon\Translate offers multilingual capabilities to applications. This component allows you to display content in different languages, based on the user’s choice of language, available by the application.
 
Usage : Introducing translations in your application is a relatively simple task. However no two implementations are the same and of course the implementation will depend on the needs of your application. Some of the options available can be an automatic detection of the visitor’s language using the server headers (parsing the HTTP_ACCEPT_LANGUAGE contents or using the getBestLanguage() method of the Phalcon\Http\Request object).
<?php
use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;
use Phalcon\Translate\InterpolatorFactory;
use Phalcon\Translate\TranslateFactory;

/**
 * @property Phalcon\Http\Request $request
 * @property Phalcon\Mvc\View     $view
 */
class UserController extends Controller
{

    public function indexAction()
    {
        $this->view->name = 'Mike';
        $this->view->t    = $this->getTranslator();
    }
    
    /**
     * @return NativeArray
     */
    private function getTranslator(): NativeArray
    {
        // Ask browser what is the best language
        $language = $this->request->getBestLanguage();
        $messages = [];
        
        $translationFile = 'app/messages/' . $language . '.php';

        if (true !== file_exists($translationFile)) {
            $translationFile = 'app/messages/en.php';
        }
        
        require $translationFile;

        $interpolator = new InterpolatorFactory();
        $factory      = new TranslateFactory($interpolator);
        
        return $factory->newInstance(
            'array',
            [
                'content' => $messages,
            ]
        );
    }
}
The getTranslator() method is available in the controller for all actions that require it. You could of course introduce a caching mechanism to store the translation adapter in your cache (based on the language selected i.e. en.cache, de-cache etc.)
Phalcon\Collection is an object oriented array. It offers speed, as well as implementations of various PHP interfaces. These are :
 
<?php

use Phalcon\Collection;

$data = [
    'colors' => [
        'red',
        'white',
        'blue',
    ],
    'year'   => 1776,
];

$collection = new Collection($data);