Phalcon Tutorial
Phalcon Tutorial
This tutorial provides an overall idea on Phalcon PHP framework and how you can use it.
Audience
This tutorial is basically developed for those who want to learn Phalcon from ground up. The
target audience of learning this framework includes students, PHP developers, web designers
and web developers.
Prerequisites
Before starting with this tutorial, the user should have knowledge of HTML, CSS and PHP along
with an understanding of MVC framework. It would be an added advantage if you have prior
exposure to other traditional frameworks like Laravel, Yii, or Codeigniter.
All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt.
Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any
contents or a part of contents of this e-book in any manner without written consent of the
publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd.
provides no guarantee regarding the accuracy, timeliness or completeness of our website or its
contents including this tutorial. If you discover any errors on our website or in this tutorial,
please notify us at [email protected]
i
Phalcon
Table of Contents
About the Tutorial ............................................................................................................................................. i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
6. PHALCON − CONTROLLERS......................................................................................................... 20
ii
Phalcon
iii
1. Phalcon − Overview Phalcon
Phalcon offers some unique features in comparison to other frameworks (traditional or existing)
in PHP. Following are some of the most prominent features of Phalcon:
A user needs quite less amount of code to take advantage of several components.
Performance
The performance of Phalcon is a feature which distinguishes it from other traditional frameworks
of PHP. Phalcon has a combination of both PHP and C; each of them can be used as a stand-
alone module. The compilation of every request is considered on a higher speed in Phalcon which
makes everything seem out-of-the-box.
1
Phalcon
C Language
Phalcon is compatible with C which increases the compilation rate. Also, C in combination with
Phalcon provides Object Relational Mapping (ORM) which provides consistency with models
created. Every model created in Phalcon is associated with the table of relational database. ORM
in Phalcon is purely implemented in C.
Developer Tools
Developer tools are used for developing web application. These tools help in generating scaffold
application with a combination of all features (C – Create, R – Read, U – Update, D – Delete).
Developer tools also include extensible support for third party libraries to be implemented in
Phalcon.
2
2. Phalcon − Environmental Setup Phalcon
Following are the steps for the installation process of Phalcon framework in Windows.
Step 1: Phalcon installation is completely dependent on dll file. DLL (Dynamic Link Library)
creates the required package and plugins for Phalcon.
Step 2: Download the required dll file. Check for the appropriate configuration of the system
and download the required dll file. After downloading the file, extract phalcon-php.dll to
/php/ext in the xampp folder.
Step 3: Edit the path in php.ini file to get it configured in a similar manner of other .dll files.
3
Phalcon
Step 4: Once the path is edited, restart the xampp/wamp stack. It will be clearly visible in the
dashboard, once the dll file is properly set.
4
Phalcon
Step 5: After downloading the package, set the path variable in the system properties.
Step 6: The dll files and Phalcon tools together help in creating the project/web application. The
user can verify through command prompt whether Phalcon framework has been successfully
installed. The output will be displayed as shown in the following screenshot.
5
Phalcon
Step 7: Once this necessary output is received, create a project using the following command:
Step 8: The web application is successfully created. Click the following URL:
http://localhost/demo1
6
Phalcon
The output will be displayed as shown in the following screenshot. It is the welcome page for
Phalcon PHP.
7
3. Phalcon − Application Structure Phalcon
In this chapter, we will discuss the Application Structure of Phalcon. Following is the complete
directory structure of a Phalcon project.
There is one root folder which is considered as the code base and is publicly available for the
web server. It is also called as web directory. Other folders outside the web root directory are
considered out of reach for the web server and for Phalcon project.
Once a project is created, the directory structure will be visible as follows in the wamp/xampp
folder. Consider for the project which we created in the previous chapter.
8
Phalcon
App
This folder consists of all vital script files and folders. The complete web application is designed
on the basis of “app” folder. The configuration files help in assisting the necessary configuration
for running the application smoothly.
Following is the detailed view of app folder for the given Phalcon web application.
Config
9
Phalcon
All the configuration required for the web application in Phalcon is comprised in this folder. It
includes information related to database connectivity, third-party libraries to be added if any,
and the services to be included.
Controllers
All the controllers are included in this folder. They are used for processing requests and
generating response.
Library
Third-party libraries for the web application (apart from the existing Phalcon framework).
Migrations
This sub-folder consists of all the files associated with data migration, which can also be used in
any other framework.
Models
Models include all the logic required to interact with the database. It is actually used for data
representation.
Views
It constitutes all the views related to the web application. These views are displayed to the end
users with the help of controllers.
Cache
This directory includes data related to caching, which helps in improving the performance.
Public
It includes all the folders for asset management purpose which comprises of CSS, JavaScript,
files to be uploaded, and some meta data.
10
Phalcon
.htaccess File
Web servers running on Apache Web Server software use .htaccess as a configuration file.
When it is placed in a directory, all the necessary configuration is loaded as soon as the server
is started.
For example, it is possible to configure a website so that it will available only to specific IP
addresses with .htaccess file.
11
4. Phalcon − Functionality Phalcon
Model View Controller (MVC) is a software design and structural pattern for developing web-
based applications. This software architectural separates the representation of information from
the user's interaction with it.
The MVC model defines the web applications with three logic layers.
Model
Models are objects which represent knowledge. There should be a one-to-one relationship
between the model and its parts. It includes all the logic to be used for database connectivity
and performing CRUD operations.
View
A view is a visual representation of its model. View interacts with the model or its parts and gets
the data necessary for the presentation from the model. This is achieved by sending requests
and receiving appropriate responses. View includes all the data that end user sees.
Controller
A controller acts as the intermediary between the user and the system (model and view). It
accepts the request from the user, through the view sends it to the model. The model
manipulates it and sends the response to the controller, which is displayed as the output to the
end user through view.
The controller receives such user output and translates it into the appropriate messages. These
messages are used by view to display as appropriate responses.
12
Phalcon
Workflow in Phalcon
The workflow in Phalcon is as follows:
The user interacts with the user interface (view) and the interaction is maintained with
the help of some method/event.
View fetches data from its model. The model has no direct interaction with view.
The user interface waits for further user interactions, which starts with a new cycle of
request and response.
13
Phalcon
Phalcon includes directories for Model, View, and Controller. The following screenshot gives a
better scenario.
All business logic is described in the controller, and the model interacts with the database which
includes all files with respect to each and every table.
Note:
14
5. Phalcon − Configuration Phalcon
The config folder of the web application includes the following files:
config.php
loader.php
services.php
config.php
It includes the configurations for database connectivity and routing as per the directory path.
<?php
/*
* Modified: preppend directory path of current file, because of this file own
different ENV under between Apache and command line.
* NOTE: please remove this comment.
*/
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?:
realpath(dirname(__FILE__) . '/../..'));
15
Phalcon
loader.php
It extends the existing class of \Phalcon\Loader(). The loader class registers the directories
which requires web application.
<?php
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerDirs(
16
Phalcon
[
$config->application->controllersDir,
$config->application->modelsDir
]
)->register();
services.php
This file associates all the functions which implement the services of a web project. It implements
Phalcon\Di interface. It also implements a dependency injection of the services by loading
them.
Basically, services.php file inside the config folder acts as a container of all services. This
interface helps in initializing all the services like database connection, setting up cookies, creating
a new session, or connecting with NoSQL database.
?php
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Php as PhpEngine;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as Flash;
/**
* Shared configuration service
*/
$di->setShared('config', function () {
return include APP_PATH . "/config/config.php";
});
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->setShared('url', function () {
$config = $this->getConfig();
17
Phalcon
$url->setBaseUri($config->application->baseUri);
return $url;
});
/**
* Setting up the view component
*/
$di->setShared('view', function () {
$config = $this->getConfig();
$view->registerEngines([
'.volt' => function ($view) {
$config = $this->getConfig();
$volt->setOptions([
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_'
]);
return $volt;
},
'.phtml' => PhpEngine::class
]);
return $view;
});
18
Phalcon
/**
* Database connection is created based in the parameters defined in the
configuration file
*/
$di->setShared('db', function () {
$config = $this->getConfig();
return $connection;
});
19
6. Phalcon − Controllers Phalcon
In MVC framework, “C” stands for the Controller which refers to the switchboards of the web
application. The actions undertaken by the controller, helps to pass parameters to the view so
that it can display and respond to the user input accordingly.
For example, if we register through a sign-up form which includes details of the user such as
username, email address and password, and click the Submit button, the data inserted or posted
by the user is sent through the controller with the help of associated action or function.
Features of a Controller
A controller accepts inputs from the view and interacts with the associated model.
It helps in updating the model's state by sending commands to the model. It can also
send commands to the associated view, which helps in changing the presentation of the
view as per the model's state.
20
Phalcon
As referred in the above screenshot, “demo” is the project associated with Phalcon PHP
framework.
Note: The class names of the controllers must have the suffix “controller”. This implies a good
naming convention which is followed in Phalcon.
By default, when the application is created in Phalcon PHP framework, it includes a controller
named “IndexController”. This controller is invoked by default to trigger the actions.
21
Phalcon
Code:
<?php
class IndexController extends ControllerBase
{
public function indexAction()
{
echo "This is my first web application in Phalcon";
}
}
Output:
22
7. Phalcon − Models Phalcon
Model in MVC architecture includes the logic of application. Model is the core interaction with the
database. It should be able to manage updating, deleting, inserting, and fetching of records as
per the user’s request.
For understanding the model interaction in Phalcon PHP framework, following steps should be
followed.
For any LAMP, WAMP, XAMPP software stack, it is quite easy to create a database with the
help of phpmyadmin database tool.
Step 2: In the phpmyadmin section, click the Databases tab, mention the database name and
further click the Create button as shown in the following screenshot.
23
Phalcon
Step 3: Once the database is created successfully, create a table which will help its association
for creating a model in Phalcon framework.
Once the table is created, its structure looks like as shown in the following screenshot.
Step 4: To create a model associated with the 'Users' table which we created in the above step,
open command prompt instance. It is important to redirect to the appropriate project path.
Before that, it is vital to check whether the database configuration has been correctly set as
shown in the following screenshot.
24
Phalcon
Step 5: Use the following command to create any model in Phalcon framework.
C:\xampp\htdocs\demo1\app\models
<?php
public $id;
/**
*
* @var string
* @Column(type="string", length=25, nullable=true)
*/
25
Phalcon
public $name;
/**
*
* @var string
* @Column(type="string", length=50, nullable=true)
*/
public $emailid;
/**
*
* @var integer
* @Column(type="integer", length=11, nullable=true)
*/
public $contactNumber;
/**
* Returns table name mapped in the model.
*
* @return string
*/
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return Users[]
*/
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return Users
*/
26
Phalcon
Step 7: The Controller interacts with the model and the view to get the necessary output.
As with the model, use the following command terminal to create a controller.
<?php
27
Phalcon
http://localhost/demo1/users
28
8. Phalcon − Views Phalcon
Views are information being presented to the end user. A view can be considered as a web page
with the appropriate response to be displayed. The response is received through the controller
which interacts with the model.
Specifically in Phalcon, the view consists of Volt code, PHP and HTML. A set of special delimiters
is available to enter in Volt mode. {% ... %} is used to execute statements such as for-loops
or assign values, and {{ ... }} prints the result of an expression to the template.
Volt
phtml
Volt
Following is the screenshot of the output we had created for the project demo1 in the previous
chapter.
It includes a set of highly integrated components, which are very beneficial in Phalcon.
29
Phalcon
Following is the code for index.volt which loads by default for any project.
<!--<div class="page-header">
<h1>Congratulations!</h1>
</div>-->
<p>This is my first web application in Phalcon </p>
<!--<p>You're now flying with Phalcon. Great things are about to happen!</p>
Hierarchical Rendering
Views in Phalcon support hierarchical rendering and Phalcon\Mvc\View is used as default
rendering component. This component uses PHP as template engine in comparison with volt files
which uses C as a template language.
These views should have .phtml extension. The default directory of views for the given project
consists of the following three files:
Action view: This view is called to execute a particular action. It is called when “show”
action is executed.
Controller layout: This view is present inside the layouts folder. For example,
C:\xampp\htdocs\demo\app\views\layouts. It invokes the method calls
associated with the appropriate controller. The code implemented in layout will be
implemented as and when required.
Main layout: This layout view will invoke the main action and it will be shown for every
controller or action within the web application.
.volt .phtml
30
Phalcon
Variables
Variables are assigned and changed in the template using 'set'.
Declaring an array
Declaring a string
Comments
Comments may also be added to a template using the {# ... #} delimiters. All text inside them
is just ignored in the final output.
Example
{% set fruits = ['Apple', 'Banana', 'Orange'] %}
<h1>Fruits</h1>
<ul>
{% for fruit in fruits %}
<li>{{ fruit|e }}</li>
{% endfor %}
</ul>
<ul>
{% for robot in robots %}
<li>{{ robot }}</li>
{% endfor %}
</ul>
31
Phalcon
Output
The code will produce the following output screen:
32
9. Phalcon − Routing Phalcon
The router component allows to define routes that are mapped to the controllers or handlers
that should receive the request. A router parses a URI as per the information received.
MVC mode
Match-only mode
The first mode is ideal for working with MVC applications. Following is the syntax to define a
route in Phalcon.
// Define a route
$router->add(
"<URI-Name>",
[
"controller" => "<controller-name>",
"action" => "<action-name>",
]
);
Example
For searching a category, let us create a route in routes.php of config folder.
33
Phalcon
Consider creating a route which will call a method login as we invoke “UsersController”. In
such a case, it is suggested to create a route which maps the given URL.
<?php
$router->add('/login', array(
'controller' => 'users',
'action' => 'login',
));
return $router;
Output
The code will produce the following output:
34
10. Phalcon − Database Connectivity Phalcon
After creation of the database, the database will be listed as shown in the following screenshot.
Phalcon uses commands for creation of models, controllers, and even projects. Let’s see how
it works.
35
Phalcon
Step 2: Configure the web application that connects to the database which we created for
managing blogs.
<?php
36
11. Phalcon − Switching Databases Phalcon
We have used a MySQL database in our application. If we wanted to change the database
software midstream, it would not be too hard, as long as we have the same data structure in
our new database.
PostgreSQL
Configure the web application which will connect to PostgreSQL database.
This can be achieved using the following code. The services will include
Phalcon\Db\Adapter\Pdo\Postgresql
use Phalcon\Db\Adapter\Pdo\Postgresql;
$config = [
'host' => 'localhost',
'dbname' => 'blog_tutorial',
'port' => 5432,
'username' => 'root',
'password' => ''
];
SQLite
For implementing SQLite connection, the configuration should be extended with
Phalcon\Db\Adapter\Pdo\Sqlite abstract class.
<?php
use Phalcon\Db\Adapter\Pdo\Sqlite;
37
Phalcon
Oracle
For implementing Oracle database connection in Phalcon, the configuration should be extended
with Phalcon\Db\Adapter\Pdo\Oracle abstract class.
<?php
use Phalcon\Db\Adapter\Pdo\Oracle;
$config = array(
"dbname" => "//localhost/blog_tutorial",
"username" => "root",
"password" => ""
);
$connection = new Phalcon\Db\Adapter\Pdo\Oracle($config);
38
12. Phalcon − Scaffolding Application Phalcon
Scaffolding usually refers to a type of code generation where we point it to a web application
database, which results in creating a basic CRUD (Create, Read, Update, Delete) application.
Before designing a CRUD application, it is important to design database tables as per the need
of the application.
Step 1: Create a scaffolding application which will include all crud operations.
39
Phalcon
The scaffold generator of Phalcon once executed will create files and folders which are described
in the following table.
40
Phalcon
<title>Blog Tutorial</title>
<link rel="stylesheet" type="text/css"
href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-
combined.min.css"/>
</li>
<?php } ?>
</ul>
</div>
</div>
</div>
<script src="http://netdna.bootstrapcdn.com/twitter-
bootstrap/2.2.1/js/bootstrap.min.js"></script>
</body>
</html>
<div align="center">
<h1>Welcome!</h1>
</div>
42
Phalcon
Users.php
<?php
/**
* @var integer
*
*/
public $id;
/**
* @var string
*
*/
public $login;
/**
* @var string
*
*/
public $password;
/**
* Initializer method for model.
*/
public function initialize()
{
$this->hasMany("id", "Posts", "users_id");
}
}
The function named ‘initialize’ helps in implementing relationship between id and users_id in
Posts table, which means that each unique user has many posts associated in the table.
43
Phalcon
Posts.php
<?php
/**
* @var integer
*
*/
public $id;
/**
* @var string
*
*/
public $title;
/**
* @var string
*
*/
public $slug;
/**
* @var string
*
*/
public $content;
/**
* @var string
*
*/
public $created;
44
Phalcon
/**
* @var integer
*
*/
public $users_id;
/**
* @var integer
*
*/
public $categories_id;
/**
* Initializer method for model.
*/
public function initialize()
{
$this->belongsTo("users_id", "Users", "id");
$this->belongsTo("categories_id", "Categories", "id");
}
}
The function ‘initialize’ includes relationship constraint mentioning the foreign key and primary
key relationship with the table.
Categories.php
<?php
/**
* @var integer
45
Phalcon
*
*/
public $id;
/**
* @var string
*
*/
public $name;
/**
* @var string
*
*/
public $slug;
/**
* Initializer method for model.
*/
public function initialize()
{
$this->hasMany("id", "Posts", "categories_id");
}
}
Similar to Users model, the ‘initialize’ function specifies that it includes many categories_id
for the given post.
UsersController.php
<?php
if ($this->request->isPost()) {
$user = Users::findFirst(array(
'login = :login: and password = :password:',
'bind' => array(
'login' => $this->request->getPost("login"),
'password' => $this->request->getPost("password")
)
));
return $this->dispatcher->forward(array(
'controller' => 'posts',
The UsersController includes functionality with log in and log out features. It checks for the
associated value in the records for “Users” table. If the value gets authenticated, the user
successfully logs in or else gets an error message.
Once logged in to the web application, the output will look as shown in the following screenshot.
We will look at implementing views in the next chapter which will focus on categories and posts
management.
48
Phalcon
Creating Views
Following is the complete structure of Blog-tutorial-master project.
The associated view for displaying the home page after the user successfully logs in is
“index.phtml”.
49
Phalcon
</head>
<body>
</div>
</div>
</div>
<script src="http://netdna.bootstrapcdn.com/twitter-
bootstrap/2.2.1/js/bootstrap.min.js"></script>
</body>
</html>
Category Management
index.phtml
<?php echo $this->getContent(); ?>
<div align="right">
<?php echo \Phalcon\Tag::linkTo(array("categories/new", "Create Categories",
"class" => "btn")) ?>
</div>
<div align="center">
<h1>Search categories</h1>
51
Phalcon
<tr>
<td align="right">
<label for="id">Id</label>
</td>
<td align="left">
<?php echo \Phalcon\Tag::textField(array("id", "type" => "numeric")) ?>
</td>
</tr>
<tr>
<td align="right">
<label for="name">Name</label>
</td>
<td align="left">
<?php echo \Phalcon\Tag::textField(array("name", "size" => 30)) ?>
</td>
</tr>
<tr>
<td align="right">
<label for="slug">Slug</label>
</td>
<td align="left">
<?php echo \Phalcon\Tag::textField(array("slug", "size" => 30)) ?>
</td>
</tr>
<tr>
<td></td>
<td><?php echo \Phalcon\Tag::submitButton(array("Search", "class" =>
"btn")) ?></td>
</tr>
</table>
</form>
</div>
52
Phalcon
Edit.phtml
<?php use Phalcon\Tag as Tag; ?>
<table width="100%">
<tr>
<td align="left"><?php echo Tag::linkTo(array("categories",
"Back", "class" => "btn")) ?></td>
<td align="right"><?php echo Tag::submitButton(array("Save",
"class" => "btn")) ?></td>
<tr>
</table>
<div align="center">
<h1>Edit categories</h1>
</div>
<table align="center">
<tr>
<td align="right">
<label for="name">Name</label>
</td>
<td align="left">
<?php echo Tag::textField(array("name", "size" => 30)) ?>
</td>
</tr>
<tr>
<td align="right">
<label for="slug">Slug</label>
</td>
<td align="left">
53
Phalcon
</form>
Search.phtml
<?php $this->getContent(); ?>
<table width="100%">
<tr>
<td align="left">
<?php echo \Phalcon\Tag::linkTo(array("categories/index", "Go
Back", "class" => "btn")); ?>
</td>
<td align="right">
<?php echo \Phalcon\Tag::linkTo(array("categories/new", "Create a
Category", "class" => "btn")); ?>
</td>
<tr>
</table>
54
Phalcon
<tr>
<td><?php echo $categories->id ?></td>
<td><?php echo $categories->name ?></td>
<td><?php echo $categories->slug ?></td>
<td><?php echo
\Phalcon\Tag::linkTo(array("categories/edit/".$categories->id, "Edit")); ?></td>
<td><?php echo
\Phalcon\Tag::linkTo(array("categories/delete/".$categories->id, "Delete")); ?></td>
</tr>
<?php }
} ?>
</tbody>
</table>
Search.phtml
<?php $this->getContent(); ?>
<table width="100%">
<tr>
<td align="left">
<?php echo \Phalcon\Tag::linkTo(array("categories/index", "Go
Back", "class" => "btn")); ?>
</td>
<td align="right">
<?php echo \Phalcon\Tag::linkTo(array("categories/new", "Create a
Category", "class" => "btn")); ?>
55
Phalcon
</td>
<tr>
</table>
</ul>
</div>
<?php
$numberPage = 1;
if ($this->request->isPost()) {
$query = Criteria::fromInput($this->di, "Categories", $_POST);
$this->session->conditions = $query->getConditions();
} else {
$numberPage = $this->request->getQuery("page", "int");
if ($numberPage <= 0) {
$numberPage = 1;
}
}
$parameters = array();
if ($this->session->conditions) {
$parameters["conditions"] = $this->session->conditions;
}
57
Phalcon
// $parameters["order"] = "id";
$categories = Categories::find($parameters);
if (count($categories) == 0) {
$this->flash->notice("The search did not find any categories");
return $this->dispatcher->forward(array(
"controller" => "categories",
"action" => "index"
));
}
$this->view->setVar("page", $page);
}
$categories = Categories::findFirst(array(
'id = :id:',
'bind' => array('id' => $id)
));
if (!$categories) {
58
Phalcon
Tag::displayTo("id", $categories->id);
Tag::displayTo("name", $categories->name);
Tag::displayTo("slug", $categories->slug);
}
}
public function createAction()
{
if (!$this->request->isPost()) {
return $this->dispatcher->forward(array(
"controller" => "categories",
"action" => "index"
));
}
return $this->dispatcher->forward(array(
"controller" => "categories",
$category = Categories::findFirst(array(
'id = :id:',
'bind' => array('id' => $this->request->getPost("id"))
));
if (!$category) {
$this->flash->error("The category does not exist");
return $this->dispatcher->forward(array(
"controller" => "categories",
"action" => "index"
));
}
$categories->id = $this->request->getPost("id");
$categories->name = $this->request->getPost("name");
$categories->slug = $this->request->getPost("slug");
if (!$categories->save()) {
foreach ($categories->getMessages() as $message) {
$this->flash->error((string) $message);
}
60
Phalcon
return $this->dispatcher->forward(array(
"controller" => "categories",
} else {
$this->flash->success("categories was updated successfully");
return $this->dispatcher->forward(array(
"controller" => "categories",
"action" => "index"
));
}
}
if (!$categories->delete()) {
foreach ($categories->getMessages() as $message){
$this->flash->error((string) $message);
}
return $this->dispatcher->forward(array(
"controller" => "categories",
"action" => "search"
61
Phalcon
));
} else {
62
Phalcon
63
13. Phalcon − Query Language Phalcon
Phalcon Query Language (PHQL) also called as PhalconQL is a high-level SQL dialect which
standardizes SQL queries for the database systems supported by Phalcon.
Example
// Instantiate the Query
$query = new Query(
"SELECT * FROM Users",
$this->getDI()
);
In the previous chapters, we have seen the working of scaffold web application named blog
tutorial. It included searching categories as per name or slug.
$numberPage = 1;
if ($this->request->isPost()) {
$query = Criteria::fromInput($this->di, "Categories", $_POST);
$this->session->conditions = $query->getConditions();
} else {
64
Phalcon
The PHQL query executed (highlighted) in the controller will fetch all the results as per the search
condition. The result of any search query as per condition will be displayed as in the screenshot.
65
Phalcon
66
14. Phalcon − Database Migration Phalcon
Database migration helps in transferring data between the specified storage types.
Database migration refers to the context of web-based applications migrating from one
platform to another.
This process usually takes place to keep a track of data which is being outdated.
<?php
/*
* Modified: preppend directory path of current file, because of this file own
different ENV under between Apache and command line.
* NOTE: please remove this comment.
*/
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?:
realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');
67
Phalcon
'application' => [
'appDir' => APP_PATH . '/',
'controllersDir' => APP_PATH . '/controllers/',
'modelsDir' => APP_PATH . '/models/',
'migrationsDir' => APP_PATH . '/migrations/',
'viewsDir' => APP_PATH . '/views/',
'pluginsDir' => APP_PATH . '/plugins/',
'libraryDir' => APP_PATH . '/library/',
'cacheDir' => BASE_PATH . '/cache/',
'baseUri' => '/dbProject/',
]
]);
Step 3: Execute the command for migration of tables included within the database “demodb”.
For now, it includes one table “users”.
Step 4: The database files migrated are stored inside the migrations directory within “app”
folder.
68
Phalcon
Users.php
<?php
use Phalcon\Db\Column;
use Phalcon\Db\Index;
use Phalcon\Db\Reference;
use Phalcon\Mvc\Model\Migration;
/**
* Class UserMigration_100
*/
class UserMigration_100 extends Migration
{
/**
* Define the table structure
*
* @return void
69
Phalcon
*/
'indexes' => [
new Index('PRIMARY', ['Id'], 'PRIMARY')
],
'options' => [
'TABLE_TYPE' => 'BASE TABLE',
'AUTO_INCREMENT' => '3',
'ENGINE' => 'InnoDB',
70
Phalcon
/**
* Run the migrations
*
* @return void
*/
public function up()
{
/**
* Reverse the migrations
*
* @return void
*/
public function down()
{
}
}
The class UserMigration_100 as shown in the example above includes associative array with
four sections which are:
As seen in the example above, version 1.0.0 of the database was successfully migrated. Phalcon
may include and run multiple migration processes depending on how the database content is
kept.
71
15. Phalcon − Cookie Management Phalcon
Cookies also known as browser cookies are small text files stored in the browser. It saves all
the information related to user identity. This information is used to validate the users once they
browse through different pages.
Session Cookies - These type of cookies stay on the browser and retain information
until the browser is closed. As soon as the browser is opened, it will be treated as a new
session for the same user.
Persistent Cookies - It includes a stipulated lifespan and remains in the browser within
the given lifespan. Those websites which use persistent cookies keep track of each and
every user, even if the browser is closed by the user.
Cookies in Phalcon
Phalcon uses Phalcon\Http\Response\Cookies as a global storage for cookies. Cookies are
stored in Phalcon while sending a request to the server.
$this->cookies->set(
"<cookie-name>",
"<cookie-value>",
time
);
Consider the following example. Using the following code, we will create cookies of the user
when the user logs in to the web application.
<?php
72
Phalcon
echo($value);
}
$this->cookies->set(
"login-action",
"abc",
time() + 15 * 86400
);
}
}
Description
Cookie named “loginAction” has been created with value “abc”.
The method “indexAction” checks whether the cookie exists and prints the value accordingly.
Encryption of Cookies
Cookies in Phalcon are encrypted before being sent to the server as a request and decrypted as
soon as we get an appropriate response from the server. This assures security of the authorized
users.
It is always suggested to avoid storing sensitive data in cookies, despite the functionality of
encryption and decryption. The configuration for encryption of cookies is included in
services.php file.
73
Phalcon
/**
* Enable encryption key for setting values of cookies
*/
$di->set(
"cookies",
function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
}
);
/**
* Set encryption key
*/
$di->set(
"crypt",
function () {
$crypt = new Crypt();
74
Phalcon
return $crypt;
}
);
Note:
75
16. Phalcon − Session Management Phalcon
Sessions are server-side information storage which helps in user interaction with the website or
web application. Each session is uniquely defined with a session ID, which is passed to the web
server whenever the browser makes an HTTP request. The session ID is paired every time with
the internal database such that all stored variables are retrieved.
Sessions in Phalcon
Phalcon uses session components which includes the wrappers to access the session data.
Session data can be isolated from other components on the same domain.
According to the application needs, the session value can be changed with the help of the
session adapter.
/**
* Start the session the first time some component requests the session service
*/
$di->setShared('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
Creating a Session
Step 1: Create a session controller for instantiating a session such that data can be retrieved
appropriately.
76
Phalcon
<?php
77
Phalcon
Removing a Session
It is possible to destroy the session or unset some variable values within the session in Phalcon.
$this->session->remove(<variable-name>);
As shown in the example above, the variable name created in the session is “data-content”
which can be removed using the following code.
$this->session->destroy();
78
17. Phalcon − Multi-Lingual Support Phalcon
It includes an adapter which helps in binding arrays and assists in reading translation messages.
Example
Let us create an output with the help of Translate component in Phalcon, which will help to
display the output as per the language suggested.
Step 1: Phalcon gives freedom to every developer to organize translation strings. Consider
keeping two different files namely: en.php (for English strings) and fr.php (for French strings).
The file will contain an array of key-value pair, where the keys are unique and values will differ
as per the translation needed.
en.php
<?php
// app/messages/en.php
$messagesContent = [
"bye" => "Good Bye",
"hi-name" => "Hello %name%",
"song" => "Your favorite song is %song%",
];
fr.php
<?php
// app/messages/fr.php
$messagesContent = [
79
Phalcon
Step 2: In an application, create a UserController which will take parameters as to which file
should be used for translation.
<?php
use Phalcon\Translate\Adapter\NativeArray;
class UserController extends \Phalcon\Mvc\Controller
{
80
Phalcon
For the default method, two parameters are taken, first is name and the second is the favorite
song of the user. Later, the function getMessageTranslation is being called which returns the
desired output.
If we want the complete output to be displayed in French, we only need to change the file name.
require "fr.php";
81
18. Phalcon − Asset Management Phalcon
Assets are all about the additional components apart from the existing framework in Phalcon.
Phalcon has an asset manager which helps to manage all the asset components like CSS or JS
files.
Method Importance
addCss(string $path, variable $local, Adds a CSS resource from the 'css' collection to
variable $filter, variable $attributes) a particular view
Example
Consider the sample project of Phalcon “vokuro” which is the best illustration for adding css
files. It will include assets/Manager for invoking all the css files.
The default controller for the project will invoke all the css files.
<?php
namespace Vokuro\Controllers;
use Phalcon\Assets\Manager;
/**
* Display the default index page.
*/
class IndexController extends ControllerBase
{
/**
* Default action. Set the public layout (layouts/public.volt)
*/
public function indexAction()
{
82
Phalcon
$this->assets->addCss("public/style.css");
$this->view->setVar('logged_in', is_array($this->auth->getIdentity()));
$this->view->setTemplateBefore('public');
}
}
Style.css
div.remember {
margin-top: 7px;
color: #969696;
}
div.remember label {
padding-top: 15px;
}
div.forgot {
margin-top: 7px;
color: #dadada;
}
footer {
background: url("../img/feature-gradient.png") no-repeat scroll center 100%
white;
color: #B7B7B7;
font-size: 12px;
padding: 30px 0;
text-align: center;
}
footer a {
margin-left: 10px;
margin-right: 10px;
}
83
Phalcon
table.signup td {
padding: 10px;
}
table.signup .alert {
margin-bottom: 0;
margin-top: 3px;
}
table.perms select {
margin-top: 5px;
margin-right: 10px;
}
table.perms label {
margin-right: 10px;
}
div.main-container {
min-height: 450px;
}
The assets will be managed inside views, which will display css files as an output.
Index.volt
{{ content() }}
{{ assets.outputCss() }}
<header class="jumbotron subhead" id="overview">
<div class="hero-unit">
<h1>Welcome!</h1>
<p class="lead">This is a website secured by Phalcon Framework</p>
<div align="right">
{{ link_to('session/signup', '<i class="icon-ok icon-white"></i> Create an
Account', 'class': 'btn btn-primary btn-large') }}
</div>
</div>
</header>
84
Phalcon
Output:
85
19. Phalcon − Working with Forms Phalcon
Forms are used in all web applications to accept inputs from the user as request. The data is
accepted as an input, then manipulated and saved in the database or any other operation is
being performed.
Phalcon includes a component named Phalcon\Forms which helps in the creation and
maintenance of forms.
Consider the example of Blog-tutorial, which we created in the previous chapters. It includes a
form which is used to create a new category.
<table width="100%">
<tr>
<td align="left"><?php echo \Phalcon\Tag::linkTo(array("categories", "Go
Back", "class" => "btn")) ?></td>
<td align="right"><?php echo \Phalcon\Tag::submitButton(array("Save",
"class" => "btn")) ?></td>
<tr>
</table>
<div align="center">
<h1>Create categories</h1>
</div>
<table align="center">
<tr>
<td align="right">
<label for="name">Name</label>
</td>
<td align="left">
<?php echo \Phalcon\Tag::textField(array("name", "size" => 30)) ?>
</td>
</tr>
<tr>
86
Phalcon
<td align="right">
<label for="slug">Slug</label>
</td>
<td align="left">
<?php echo \Phalcon\Tag::textField(array("slug", "size" => 30)) ?>
</td>
</tr>
</table>
</form>
The input fields of form are rendered with the help of Phalcon/tag component. Each element
in the form can be rendered as per the requirement of the developer.
echo $form->render(element-name)
Validation:
Once the values are rendered in the controller, the values will be entered in the database with
the help of models. Phalcon forms are integrated with the validation component to offer instant
validation. Built-in or custom validators can be set to each element.
<?php
use Phalcon\Forms\Element\Text;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\StringLength;
87
Phalcon
$name->addValidator(
new PresenceOf(
[
"message" => "name is required",
]
)
);
$form->add($name);
88
20. Phalcon − Object Document MapperPhalcon
Before starting with the concepts of Object Relational Mapper (ORM) and Object Document
Mapper (ODM), it is important to understand the difference between SQL and NoSQL databases.
The following table highlights the differences between SQL and NoSQL:
SQL NoSQL
They are also termed as Relational They are called as non-relational or distributed
Databases (RDBMS) database
Phalcon has the ability to map with SQL and NoSQL databases. This is achieved with the help of
Object Document Mapper (ODM) for NoSQL database and Object Relational Mapper (ORM) for
SQL database.
In Phalcon, ORM concept comprises of creating a model associated with the given table-name
as we have seen in the previous chapters. It follows all the referential integrity constraints.
Example
Step 1: Create a database of MongoDB named “test”. We will use this database to map with
and get the appropriate response.
89
Phalcon
90
Phalcon
Step 2: Check for the inserted records in the database. The command associated with it is:
db.collection.find()
It is observed that every document is mapped with ObjectId which is a feature of ODM. The
value of ObjectId is unique and later used to fetch all the data stored with respect to that
particular Id.
Step 3: Set up model for the database created. A model is a class which extends
Phalcon\Mvc\Collection. Test.php model will include the following code.
<?php
use Phalcon\Mvc\Collection;
91
Phalcon
return $mongo->selectDB("test");
},
true
);
// Connecting to a domain socket, falling back to localhost connection
$di->set(
"mongo",
function () {
$mongo = new MongoClient(
"mongodb:///tmp/mongodb-27017.sock,localhost:27017"
);
return $mongo->selectDB("test");
},
true
);
Step 5: Print the values with respect to ObjectId with the help of TestController.php
<?php
use Phalcon\Mvc\Controller;
92
Phalcon
echo $test->data;
}
}
The output will display data which matches the objectId. If the objectId is not matched as per
the records in the documents, then the appropriate output will not be displayed as the number
of records is fetched.
93
21. Phalcon − Security Features Phalcon
Phalcon provides security features with the help of Security component, which helps in
performing certain tasks like password hashing and Cross-Site Request Forgery (CSRF).
Hashing Password
Hashing can be defined as the process of converting a fixed length bit string into a specified
length in such a way that it cannot be reversed. Any change in the input string will change the
value of hashed data.
Decryption of hashed data takes place by taking the value entered by the user as input and
comparing hash form of the same. Usually for any web-based applications, storing passwords as
plain text is a bad practice. It is prone to third-party attacks as those who have access to the
database can easily procure passwords for any user.
Phalcon provides an easy way to store passwords in encrypted form which follows an algorithm
like md5, base64 or sh1.
As seen in the previous chapters, where we created a project for blogs. The login screen accepts
input as username and password for the user. To receive the passwords from the user and
decrypt it in a particular form, the following code snippet is used.
The decrypted password is then matched with the password accepted as input from the user. If
the value matches, the user can successfully log in to web application else an error message is
displayed.
<?php
$login = $this->request->getPost("login");
$password = $this->request->getPost("password");
94
Phalcon
$user->login = $login;
$user->save();
}
if ($this->request->isPost()) {
$user = Users::findFirst(array(
'login = :login: and password = :password:',
'bind' => array(
'login' => $this->request->getPost("login"),
'password' => sha1($this->request->getPost("password"))
)
));
$this->session->set('auth', $user->id);
return $this->dispatcher->forward(array(
95
Phalcon
The passwords stored in the database are in an encrypted format of sh1 algorithm.
Once the user enters an appropriate username and password, the user can access the system,
else an error message is displayed as a validation.
96
Phalcon
The data in each form is secured with the help of token generation. The token generated is
random and it is matched with the token to which we are sending the form data (mostly outside
the web application through POST method).
Code:
</form>
Note: It is important to use session adapter while sending tokens of form, as all the data will
be maintained in the session.
/**
* Start the session the first time some component request the session service
*/
$di->setShared('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
97