Wednesday, March 8, 2017

Phalcon - Quick Guide

Phalcon - Overview

Phalcon is introduced as one of the recent frameworks of PHP, developed by a group of enthusiastic developers. Phalcon is a loosely coupled framework, which means it allows its objects to be treated like glue components, based on the needs of application.

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 −
  • It is a full stack open source framework.
  • A user needs quite less amount of code to take advantage of several components.
  • It can be used to create an independent framework as required. For example, if we just need Phalcon's Cache component, we can use it in any application written either in pure PHP or using a framework.
  • For a developer having knowledge of Model-View-Controller (MVC) and Object- Relational Modeling (ORM), working with Phalcon is like a cakewalk.

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 standalone module. The compilation of every request is considered on a higher speed in Phalcon which makes everything seem out-of-the-box.
Performance

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.

Object Relational Mapping

Phalcon supports a wide range of databases. It is not limited to access of relational databases. It supports both relational and non-relational databases which is like adding a feather to the cap of Phalcon framework.

Phalcon Vs Other Frameworks

The following table highlights how Phalcon differs from other popular frameworks such as Yii and Laravel.

Yii Laravel Phalcon
Type of Projects Yii helps in creating large scale projects like forums, portals, CMS, RESTful web services, etc. Laravel is used for building web applications. It is known for exquisite and sophisticated syntax. Phalcon is used to design variety of projects.
Database Support Yii supports all relational and non-relational databases. Laravel supports all relational databases. Phalcon gives equal support to relational and non-relational databases.
Language Yii framework is purely written in PHP. Laravel is written in PHP and follows MVC pattern. Phalcon includes both PHP and C.
Scalability Yii is quite scalable for small and medium projects. Scalability is high for Laravel with all kinds of projects. Good for medium projects.
Performance Comparatively low. High but less in comparison with Phalcon. High Performance.

Phalcon - Environmental Setup

Prerequisites − We need WAMP/LAMP/MAMP or XAMPP stack for this framework.
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.
The following link is used for downloading dll file − https://phalconphp.com/en/download
Phalcon for Windows 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.
Phalcon php 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.
dll file Step 5 − After downloading the package, set the path variable in the system properties.
Set the Path 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.
Web Application Step 7 − Once this necessary output is received, create a project using the following command −
phalcon create-project <project-name> 
The following output will be displayed.
Output Step 8 − The web application is successfully created. Click the following URL − http://localhost/demo1
The output will be displayed as shown in the following screenshot. It is the welcome page for Phalcon PHP.
Welcome Page

Phalcon - Application Structure

In this chapter, we will discuss the Application Structure of Phalcon. Following is the complete directory structure of a Phalcon project.
Structure 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.
demo1 Following are the folders and sub-folders of the project.

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.
App It consists of config, controllers, library, migrations, models and views.

Config

Config 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).
Library

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.
Public

.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.

Phalcon - Functionality

Model View Controller (MVC) is a software design and structural pattern for developing webbased 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.
MVC

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.

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.
  • These methods and events are handled by the controller.
  • The controller accesses the model by updating the user’s action.
  • View uses the model to generate an appropriate output.
  • 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.
Workflow Phalcon includes directories for Model, View, and Controller. The following screenshot gives a better scenario.
Directories 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
  • All the controllers created in Phalcon web application extends Phalcon\Mvc\Controller.
  • All the models associated with the database tables extends \Phalcon\Mvc\Model.

Phalcon - Configuration

The config folder of the web application includes the following files −
  • config.php
  • loader.php
  • services.php
Config

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__) . '/../..')); 
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');  

return new \Phalcon\Config([ 
   'database' => [ 
      'adapter'     => 'Mysql', 
      'host'        => 'localhost', 
      'username'    => 'root', 
      'password'    => '', 
      'dbname'      => 'test', 
      'charset'     => 'utf8', 
   ], 
   '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'        => '/demo1/', 
   ] 
]);

loader.php

It extends the existing class of \Phalcon\Loader(). The loader class registers the directories which requires web application.
<?php  
$loader = new \Phalcon\Loader();  

/** 
   * We're a registering a set of directories taken from the configuration file 
*/ 

$loader->registerDirs( [ 
      $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(); 
      $url = new UrlResolver(); 
      $url->setBaseUri($config->application->baseUri);  
   return $url; 
});  

/** 
   * Setting up the view component 
*/ 
   
$di->setShared('view', function () { 
   $config = $this->getConfig();  
   $view = new View(); 
   $view->setDI($this); 
   $view->setViewsDir($config->application->viewsDir);  
   
   $view->registerEngines([ 
      '.volt' => function ($view) { 
         $config = $this->getConfig();  
         $volt = new VoltEngine($view, $this);  
         
         $volt->setOptions([ 
            'compiledPath' => $config->application->cacheDir, 
            'compiledSeparator' => '_' 
         ]);  
         return $volt; 
      }, 
      '.phtml' => PhpEngine::class  
   ]);  
   return $view; 
}); 

/** 
   * Database connection is created based in the parameters defined in the configuration 
      file 
*/ 

$di->setShared('db', function () { 
   $config = $this->getConfig();  
   $class = 'Phalcon\Db\Adapter\Pdo\\' . $config->database->adapter; 
   $connection = new $class([ 
      'host'     => $config->database->host, 
      'username' => $config->database->username, 
      'password' => $config->database->password, 
      'dbname'   => $config->database->dbname, 
      'charset'  => $config->database->charset 
   ]);  
   return $connection; 
});

No comments:

Post a Comment