SlideShare a Scribd company logo
1 of 87
Phalcon
Giant Killer
Jacksonfdam
http://about.me/jacksonfdam
https://bitbucket.org/jacksonfdam
https://github.com/jacksonfdam
http://linkedin.com/in/jacksonfdam
@jacksonfdam
Why?
• Use of frameworks has become mandatory in professional
development with PHP
• They offer a philosophy and organized structures to easily
maintain projects writing less code and making work more
fun
How PHP works?
1. PHP have dynamic and weak typing discipline
2. PHP is interpreted (not compiled)
3. Every time a script is loaded, should be interpreted by PHP
4. If a bytecode cache (like APC) isn’t used, syntax checking is
performed every time
How traditional php frameworks works?
1. Many files with classes and functions are read at every request made. Disk
reading is expensive in terms of performance
2. Modern frameworks use lazy loading technique (autoload) for load and execute
only code needed
3. Continuous loading/interpreting could be expensive and impact your
application performance
4. When you use a framework most of the code remain the same across
development. Why load and interpret it every time?
How a PHP C extension works?
1. C extensions are loaded together with PHP one time, on the web server
dispatch process
2. Classes and functions provided by the extension are ready to use for any
application
3. The code isn’t interpreted because it is compiled to a specific platform and
processor
What is Phalcon?
Phalcon is an open source, full stack framework for PHP 5
written as a C-extension, optimized for high performance. You
don’t need to learn or use the C language, since the
functionality is exposed as PHP classes ready for you to use.
Phalcon also is loosely coupled, allowing you to use its objects
as glue components based on the needs of your application.
How Phalcon works?
1. Components are loosely coupled. You may use the components you want
without depending on a full stack
2. Low-level optimizations provide the lowest overhead for MVC-based
applications
3. Interact with databases with maximum performance by using a C-language
ORM for PHP
4. Phalcon is directly engaged with PHP, so it can directly access internal
structures optimizing execution as well
What is Phalcon?
Compare how Phalcon is faster than other
frameworks
Traditional Frameworks Phalcon
Interpretation of hundreds
or thousands of PHP lines
on each request
YES NO
Load dozens of files in
each request
YES NO
Checking the existence of
functions, methods,
classes, constants at each
request
YES NO
Low-level optimizations
gaining microseconds for
each request
NO YES
Framework Benchmark
Framework Benchmark
<h1>Hello!</h1>
Test Environment
Operative System: Mac OS X Snow Leopard 10.6.8
• Web Server: Apache httpd 2.2.21
• PHP: 5.3.8 + APC 3.1.9 (Without Xdebug)
• CPU: 3.06 Ghz Intel Core 2 Duo
• Main Memory: 4GB 1067 MHz DDR3
• Hard Disk: 500GB SCSI/SAS HDD
Framework Benchmark
ab -n 1000 -c 5 http://localhost/bench/phalcon
Framework/Requests per Second
Framework Total Requests/Average Time
Number of Interpreted Files per Request
Allocated Memory per Request
Installation
Installation
To use phalcon on Windows you can download a DLL library. Edit your php.ini file
and then append at the end:
extension=php_phalcon.dll
Restart your webserver.
Requirements
Prerequisite packages are:
PHP >= 5.3 development resources
GCC compiler (Linux/Solaris)
Git (if not already installed in your system - unless you download the package
from GitHub and upload it on your server via FTP/SFTP)
Requirements
Specific packages for common platforms:
#Ubuntu
sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql
#Suse
sudo yast -i gcc make autoconf2.13 php5-devel php5-pear php5-mysql
#CentOS/RedHat/Fedora
sudo yum install php-devel pcre-devel gcc make
#Solaris
pkg install gcc-45 php-53 apache-php53
Compilation
git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build
sudo ./install
Configure
Add extension to your php configuration:
#Suse: Add this line in your php.ini
extension=phalcon.so
#Centos/RedHat/Fedora: Add a file called phalcon.ini in /etc/php.d/ with this content:
extension=phalcon.so
#Ubuntu/Debian: Add a file called 30-phalcon.ini in /etc/php.d/ with this content:
extension=phalcon.so
#Debian with php5-fpm: Add a file called 30-phalcon.ini in /etc/php5/fpm/conf.d/30-phalcon.ini with this content:
extension=phalcon.so
Restart the webserver.
Configure
Phalcon automatically detects your architecture, however, you can force the compilation for a specific architecture:
cd cphalon/build
sudo ./install 32bits
sudo ./install 64bits
sudo ./install safe
Mac OS X
On a Mac OS X system you can compile and install the extension from the source code:
Requirements
Prerequisite packages are:
PHP >= 5.3 development resources
XCode
#brew
brew tap homebrew/homebrew-php
brew install php53-phalcon
brew install php54-phalcon
brew install php55-phalcon
brew install php56-phalcon
#MacPorts
sudo port install php53-phalcon
sudo port install php54-phalcon
sudo port install php55-phalcon
sudo port install php56-phalcon
Installation on XAMPP
XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl.
Once you download XAMPP, all you have to do is extract it and start using it.
Below are detailed instructions on how to install Phalcon on XAMPP for Windows.
Using the latest XAMPP version is highly recommended.
Installation on XAMPP
XAMPP is always releasing 32 bit versions of Apache and PHP. You will need to
download the x86 version of Phalcon for Windows from the download section.
After downloading the Phalcon library you will have a zip file like the one shown
below:
Installation on XAMPP
Extract the library from the archive to get the Phalcon DLL:
Installation on XAMPP
Copy the file php_phalcon.dll to the PHP extensions. If you have installed XAMPP
in the c:xampp folder, the extension needs to be in c:xamppphpext
Installation on XAMPP
Edit the php.ini file, it is located at C:xamppphpphp.ini. It can be edited with Notepad or a
similar program. We recommend Notepad++ to avoid issues with line endings. Append at
the end of the file: extension=php_phalcon.dll and save it.
Installation on XAMPP
Restart the Apache Web Server from the XAMPP Control Center. This will load the new PHP
configuration.
Installation on XAMPP
Open your browser to navigate to
http://localhost. The XAMPP welcome
page will appear. Click on the link
phpinfo().
phpinfo() will output a significant amount
of information on screen about the current
state of PHP. Scroll down to check if the
phalcon extension has been loaded
correctly.
If you can see the phalcon version in the
phpinfo() output, congrats!, You are now
flying with Phalcon.
Creating a project
File structure
Phalcon does not impose a particular file structure for application development.
Due to the fact that it is loosely coupled, you can implement Phalcon powered
applications with a file structure you are most comfortable using.
Creating a project
For the purposes of this tutorial and as a starting point, we suggest the following
structure:
lab01/
app/
controllers/
models/
views/
public/
css/
img/
js/
Beautiful URLs
#/tutorial/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
#/tutorial/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
Bootstrap
<?php
try {
//Register an autoloader
$loader = new PhalconLoader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
//Create a DI
$di = new PhalconDIFactoryDefault();
//Setup the view component
$di->set('view', function(){
$view = new PhalconMvcView();
$view->setViewsDir('../app/views/');
return $view;
});
//Setup a base URI so that all generated URIs
include the "tutorial" folder
$di->set('url', function(){
$url = new PhalconMvcUrl();
$url->setBaseUri('/lab01//');
return $url;
});
//Handle the request
$application = new PhalconMvcApplication($di);
echo $application->handle()->getContent();
} catch(PhalconException $e) {
echo "PhalconException: ", $e->getMessage();
}
Creating a Controller
By default Phalcon will look for a controller named “Index”. It is the starting point when no controller or action has been passed in the
request. The index controller (app/controllers/IndexController.php) looks like:
<?php
class IndexController extends PhalconMvcController
{
public function indexAction()
{
echo "<h1>Hello!</h1>";
}
}
Creating a Controller
In our case (app/views/index/index.phtml):
<?php echo "<h1>Hello!</h1>";
Our controller (app/controllers/IndexController.php) now has an empty action definition:
<?php
class IndexController extends PhalconMvcController
{
public function indexAction()
{
}
}
Creating a Model
Phalcon brings the first ORM for PHP entirely written in C-language. Instead of
increasing the complexity of development, it simplifies it.
Before creating our first model, we need to create a database table outside of
Phalcon to map it to. A simple table to store registered users can be defined like this:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(70) NOT NULL,
`email` varchar(70) NOT NULL,
PRIMARY KEY (`id`)
);
Creating a Model
A model should be located in the app/models directory (app/models/Users.php). The
model maps to the “users” table:
<?php
class Users extends PhalconMvcModel
{
}
Setting a Database Connection
In order to be able to use a database connection and subsequently access
data through our models, we need to specify it in our bootstrap process. A
database connection is just another service that our application has that can
be used for several components:
Setting a Database Connection
<?php
try {
//Register an autoloader
$loader = new PhalconLoader();
$loader->registerDirs(array(
'../app/controllers/',
'../app/models/'
))->register();
//Create a DI
$di = new PhalconDIFactoryDefault();
/
/Setup the database service
$di->set('db', function(){
return new
PhalconDbAdapterPdoMysql(array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "test_db"
));
});
//Setup the view component
$di->set('view', function(){
$view = new PhalconMvcView();
$view->setViewsDir('../app/views/');
return $view;
});
//Setup a base URI so that all generated URIs include
the "tutorial" folder
$di->set('url', function(){
$url = new PhalconMvcUrl();
$url->setBaseUri('/tutorial/');
return $url;
});
//Handle the request
$application = new PhalconMvcApplication($di);
echo $application->handle()->getContent();
} catch(Exception $e) {
echo "PhalconException: ", $e->getMessage();
}
Volt: Template Engine
Volt is an ultra-fast and designer friendly templating language written in C for PHP. It
provides you a set of helpers to write views in an easy way. Volt is highly integrated
with other components of Phalcon, just as you can use it as a stand-alone component
in your applications.
Volt: Template Engine
Volt: Template Engine
Volt views are compiled to pure PHP code, so basically they save the effort of writing PHP code manually:
{# app/views/products/show.volt #}{% block last_products %}{% for product in products %}
* Name: {{ product.name|e }}
{% if product.status == "Active" %}
Price: {{ product.price + product.taxes/100 }}
{% endif %}{% endfor %}{% endblock %}
Phalcon Query Language (PHQL)
Phalcon Query Language, PhalconQL or simply PHQL is a high-level, object-oriented
SQL dialect that allows to write queries using a standardized SQL-like language.
PHQL is implemented as a parser (written in C) that translates syntax in that of the
target RDBMS.
Phalcon Query Language (PHQL)
In PHQL, we’ve implemented a set of features to make your access to databases
more secure:
• Bound parameters are part of the PHQL language helping you to secure your code
• PHQL only allows one SQL statement to be executed per call preventing injections
• PHQL ignores all SQL comments which are often used in SQL injections
• PHQL only allows data manipulation statements, avoiding altering or dropping
tables/databases by mistake or
externally without authorization
• PHQL implements a high-level abstraction allowing you to handle tables as models
and fields as class attributes
Phalcon Query Language (PHQL)
Creating PHQL Queries
PHQL queries can be created just by instantiating the class PhalconMvcModelQuery:
<?php
// Instantiate the Query
$query = new PhalconMvcModelQuery("SELECT * FROM Cars", $this->getDI());
// Execute the query returning a result if any
$cars = $query->execute();
Phalcon Query Language (PHQL)
Selecting Records
As the familiar SQL, PHQL allows querying of records using the SELECT statement
we know, except that instead of specifying tables, we use the models classes:
<?php
$query = $manager->createQuery("SELECT * FROM Cars ORDER BY Cars.name");
$query = $manager->createQuery("SELECT Cars.name FROM Cars ORDER BY Cars.name")
Phalcon Query Language (PHQL)
Result Types
Depending on the type of columns we query, the result type will vary. If you retrieve a
single whole object, then the
object returned is a PhalconMvcModelResultsetSimple. This kind of resultset is a
set of complete model objects:
<?php
$phql = "SELECT c.* FROM Cars AS c ORDER BY c.name";
$cars = $manager->executeQuery($phql);
foreach ($cars as $car) {
echo "Name: ", $car->name, "n";
}
Phalcon Query Language (PHQL)
Result Types
Or:
<?php
$cars = Cars::find(array("order" => "name"));
foreach ($cars as $car) {
echo "Name: ", $car->name, "n";
}
Phalcon Query Language (PHQL)
Inserting Data
Phalcon doesn’t only transform the PHQL statements into SQL. All events and
business rules defined in the model are executed as if we created individual objects
manually. Let’s add a business rule on the model cars.
A car cannot cost less than $ 10,000:
Phalcon Query Language (PHQL)
Inserting Data
<?php
use PhalconMvcModelMessage;
class Cars extends PhalconMvcModel
{
public function beforeCreate()
{
if ($this->price < 10000)
{
$this->appendMessage(new Message("A car cannot cost less than $ 10,000"));
return false;
}
}
}
Phalcon Query Language (PHQL)
Inserting Data
If we made the following INSERT in the models Cars, the operation will not be successful
because the price does not
meet the business rule that we implemented:
<?php
$phql = "INSERT INTO Cars VALUES (NULL, ’Nissan Versa’, 7, 9999.00, 2012, ’Sedan’)";
$result = $manager->executeQuery($phql);
if ($result->success() == false)
{
foreach ($result->getMessages() as $message)
{
echo $message->getMessage();
}
}
Phalcon Query Language (PHQL)
Updating Data
Updating rows is very similar than inserting rows. As you may know, the instruction to
update records is UPDATE.
When a record is updated the events related to the update operation will be executed
for each row.
Phalcon Query Language (PHQL)
Updating Data
<?php
// Updating a single column
$phql = "UPDATE Cars SET price = 15000.00 WHERE id = 101";
$manager->executeQuery($phql);
// Updating multiples columns
$phql = "UPDATE Cars SET price = 15000.00, type = ’Sedan’ WHERE id = 101";
$manager->executeQuery($phql);
Phalcon Query Language (PHQL)
Updating Data
<?php
// Using placeholders
$phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2";
$manager->executeQuery($phql, array(
0 => 7000.00,
1 => ’Sedan’,
2 => 5
));
Phalcon Query Language (PHQL)
Updating Data
An UPDATE statement performs the update in two phases:
• First, if the UPDATE has a WHERE clause it retrieves all the objects that match
these criteria,
• Second, based on the queried objects it updates/changes the requested attributes
storing them to the relational database
Phalcon Query Language (PHQL)
Deleting Data
When a record is deleted the events related to the delete operation will be executed
for each row:
<?php
// Deleting a single row
$phql = "DELETE FROM Cars WHERE id = 101";
$manager->executeQuery($phql);
// Deleting multiple rows
$phql = "DELETE FROM Cars WHERE id > 100";
$manager->executeQuery($phql);
Phalcon Query Language (PHQL)
Deleting Data
When a record is deleted the events related to the delete operation will be executed
for each row:
<?php
// Using placeholders
$phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:";
$manager->executeQuery(
$phql,
array(
’initial’ => 1,
’final’ => 100
)
);
Phalcon Query Language (PHQL)
Deleting Data
DELETE operations are also executed in two phases like UPDATEs.
Phalcon Query Language (PHQL)
Creating queries using the Query Builder
//Getting a whole set
$robots = $this->modelsManager->createBuilder()
->from(’Robots’)
->join(’RobotsParts’)
->orderBy(’Robots.name’)
->getQuery()
->execute();
Phalcon Query Language (PHQL)
Creating queries using the Query Builder
//Getting the first row
$robots = $this->modelsManager->createBuilder()
->from(’Robots’)
->join(’RobotsParts’)
->orderBy(’Robots.name’)
->getQuery()
->getSingleResult();
Phalcon Query Language (PHQL)
PHQL Lifecycle
Being a high-level language, PHQL gives developers the ability to personalize and
customize different aspects in order to suit their needs. The following is the life cycle
of each PHQL statement executed:
• The PHQL is parsed and converted into an Intermediate Representation (IR) which
is independent of the SQL implemented by database system
• The IR is converted to valid SQL according to the database system associated to
the model
• PHQL statements are parsed once and cached in memory. Further executions of
the same statement result in a slightly faster execution
Routing
The router component allows defining routes that are mapped to controllers or
handlers that should receive the request.
A router simply parses a URI to determine this information. The router has two
modes: MVC mode and match-only mode. The first mode is ideal for working with
MVC applications.
Routing
Defining Routes
PhalconMvcRouter provides advanced routing capabilities. In MVC mode, you can
define routes and map them to controllers/actions that you require. A route is defined
as follows:
Routing
An application can have many paths, define routes one by one can be a cumbersome task. In these cases we
can create more flexible routes:
<?php
// Create the router
$router = new PhalconMvcRouter();
//Define a route
$router->add(
"/admin/:controller/a/:action/:params",
array(
"controller" => 1,
"action" => 2,
"params" => 3,
)
);
Routing
Parameters with Names
The example below demonstrates how to define names to route parameters:
<?php
$router->add(
"/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params",
array(
"controller" => "posts",
"action" => "show",
"year" => 1, // ([0-9]{4})
"month" => 2, // ([0-9]{2})
"day" => 3, // ([0-9]{2})
"params" => 4, // :params
)
);
Routing
HTTP Method Restrictions
When you add a route using simply add(), the route will be enabled for any HTTP method. Sometimes we can
restrict a route to a specific method, this is especially useful when creating RESTful applications:
<?php
// This route only will be matched if the HTTP method is GET
$router->addGet("/products/edit/{id}", "Products::edit");
// This route only will be matched if the HTTP method is POST
$router->addPost("/products/save", "Products::save");
// This route will be matched if the HTTP method is POST or PUT
$router->add("/products/update")->via(array("POST", "PUT"));
Routing
Not Found Paths
If none of the routes specified in the router are matched, you can define a group of paths to be used in this
scenario:
<?php
//Set 404 paths
$router->notFound(array(
"controller" => "index",
"action" => "route404"
));
DRY or DIE
Don't Repeat Yourself (DRY) or Duplication is Evil (DIE) is a principle of software development
KISS
KISS is an acronym for the design principle "Keep it simple, Stupid!".
SOLID
The principles when applied together intends to make it more likely that a programmer will create a system
that is easy to maintain and extend over time
SOCKETS
Ratchet - WebSockets for PHP
Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directional
applications between clients and servers over WebSockets.
http://socketo.me/
Background Jobs
Setup background jobs with Phalcon and Resque
https://github.com/doshimehul/phalcon-resque
RESTful
Phalcon REST provides a framework to build your own API upon, core functionalities include:
• Response formatting using Fractal's Transformer concept
(I got this concept from a book written by Phil Sturgeon)
• Authentication sessions using Json Web Token
• Access Control List using ACL class Phalcon provides
• Username and password authentication service
• Google authentication service
• Documentation generator based on docblock annotations
http://phalconist.com/olivierandriessen/phalcon-rest
RESTful
What is Fractal?
Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful
APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc.
When building an API it is common for people to just grab stuff from the database and pass it to
json_encode().
http://fractal.thephpleague.com/
Phalcon Micro-Start
Phalcon Micro-Start
A more practical example of the start of a Phalcon micro application
What's Included?
Basic page example
Partial views (Simple view engine)
URL with params
JSON return
Cached view
Redirect URL
https://github.com/james2doyle/phalcon-micro-start
Phalcon Docker
Docker Phalcon Apache2
Docker image based on Ubuntu 14.04 (trusty) with the latest stable Phalcon PHP Framework with apache 2.4
webserver installed.
https://github.com/szeist/docker-phalcon-apache2
Vagrant
Create and configure lightweight, reproducible, and portable development environments. Vagrant will change
how you work
http://www.vagrantup.com/
Puppet
Puppet is IT automation software that helps system administrators manage infrastructure throughout its
lifecycle, from provisioning and configuration to orchestration and reporting. Using Puppet, you can easily
automate repetitive tasks, quickly deploy critical applications, and proactively manage change, scaling from
10s of servers to 1000s, on-premise or in the cloud.
http://puppetlabs.com/puppet/what-is-puppet
PuPHPet
PuPHPet, an excellent GUI tool providing a simple wizard, which creates a Puppet-powered Vagrant
configuration, usable immediately.Originally started by Juan Treminio, PuPHPet makes creating
environments perfectly tailored for PHP developers on stacks such as {W,M,L}AMP dead simple.
https://puphpet.com/
Provisioning Phalcon
PuPHPet is an absolutely awesome tool in getting up and running with a development environment really
fast, and offers some very neat default options.
But what if we want to step outside the defaults? What if we'd, for example, like to install a PHP extension
that isn't part of the default distribution and doesn't exist in package managers?
http://docs.vagrantup.com/v2/provisioning/index.html
Phalconist
Resources catalog for Phalcon framework
http://phalconist.com/
Referencias
http://docs.phalconphp.com/en/
http://www.sitepoint.com/build-virtual-machines-easily-puphpet/
http://www.sitepoint.com/provisioning-phalcon-tools-vagrant/
http://www.sitepoint.com/php-rabbitmq-advanced-examples/
Thank you!
jacksonfdam@gmail.com
t
f
in
Email Socialmedia
@jacksonfdam
@mafra.jackson
@jacksonfdam

More Related Content

What's hot

PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with ComposerAdam Englander
 
Reverse Installing CPAN
Reverse Installing CPANReverse Installing CPAN
Reverse Installing CPANbrian d foy
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flaskjuzten
 
Road to CakePHP 3.0
Road to CakePHP 3.0Road to CakePHP 3.0
Road to CakePHP 3.0markstory
 
Php psr standard 2014 01-22
Php psr standard 2014 01-22Php psr standard 2014 01-22
Php psr standard 2014 01-22Võ Duy Tuấn
 
Composer | PHP Dependency Manager
Composer | PHP Dependency ManagerComposer | PHP Dependency Manager
Composer | PHP Dependency ManagerUjjwal Ojha
 
2021.laravelconf.tw.slides1
2021.laravelconf.tw.slides12021.laravelconf.tw.slides1
2021.laravelconf.tw.slides1LiviaLiaoFontech
 
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web server
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web serverNginx 0.8.x + php 5.2.13 (fast cgi) setup web server
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web serverwruben
 
Dependency management with Composer
Dependency management with ComposerDependency management with Composer
Dependency management with ComposerJason Grimes
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmersjphl
 
Create your own composer package
Create your own composer packageCreate your own composer package
Create your own composer packageLattapon Yodsuwan
 
Running PHP on Windows Technical Overview
Running PHP on Windows Technical OverviewRunning PHP on Windows Technical Overview
Running PHP on Windows Technical OverviewWes Yanaga
 
[Part 1] automation of home appliances using raspberry pi – software installa...
[Part 1] automation of home appliances using raspberry pi – software installa...[Part 1] automation of home appliances using raspberry pi – software installa...
[Part 1] automation of home appliances using raspberry pi – software installa...Azilen Technologies Pvt. Ltd.
 
Setting advanced PHP development environment
Setting advanced PHP development environmentSetting advanced PHP development environment
Setting advanced PHP development environmentKapil Sharma
 

What's hot (20)

PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with Composer
 
Reverse Installing CPAN
Reverse Installing CPANReverse Installing CPAN
Reverse Installing CPAN
 
Quick flask an intro to flask
Quick flask   an intro to flaskQuick flask   an intro to flask
Quick flask an intro to flask
 
Road to CakePHP 3.0
Road to CakePHP 3.0Road to CakePHP 3.0
Road to CakePHP 3.0
 
Php psr standard 2014 01-22
Php psr standard 2014 01-22Php psr standard 2014 01-22
Php psr standard 2014 01-22
 
Composer | PHP Dependency Manager
Composer | PHP Dependency ManagerComposer | PHP Dependency Manager
Composer | PHP Dependency Manager
 
Flask
FlaskFlask
Flask
 
2021.laravelconf.tw.slides1
2021.laravelconf.tw.slides12021.laravelconf.tw.slides1
2021.laravelconf.tw.slides1
 
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web server
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web serverNginx 0.8.x + php 5.2.13 (fast cgi) setup web server
Nginx 0.8.x + php 5.2.13 (fast cgi) setup web server
 
Dependency management with Composer
Dependency management with ComposerDependency management with Composer
Dependency management with Composer
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
An Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP ProgrammersAn Introduction to Websphere sMash for PHP Programmers
An Introduction to Websphere sMash for PHP Programmers
 
Create your own composer package
Create your own composer packageCreate your own composer package
Create your own composer package
 
Running PHP on Windows Technical Overview
Running PHP on Windows Technical OverviewRunning PHP on Windows Technical Overview
Running PHP on Windows Technical Overview
 
PHP programmimg
PHP programmimgPHP programmimg
PHP programmimg
 
[Part 1] automation of home appliances using raspberry pi – software installa...
[Part 1] automation of home appliances using raspberry pi – software installa...[Part 1] automation of home appliances using raspberry pi – software installa...
[Part 1] automation of home appliances using raspberry pi – software installa...
 
AtoM's Command Line Tasks - An Introduction
AtoM's Command Line Tasks - An IntroductionAtoM's Command Line Tasks - An Introduction
AtoM's Command Line Tasks - An Introduction
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Wt vs phalcon
Wt vs phalconWt vs phalcon
Wt vs phalcon
 
Setting advanced PHP development environment
Setting advanced PHP development environmentSetting advanced PHP development environment
Setting advanced PHP development environment
 

Similar to Phalcon 2 - PHP Brazil Conference

Php through the eyes of a hoster confoo
Php through the eyes of a hoster confooPhp through the eyes of a hoster confoo
Php through the eyes of a hoster confooCombell NV
 
Updating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_ServerUpdating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_Servertutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Updating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_ServerUpdating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_Servertutorialsruby
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida realPHP Conference Argentina
 
Php Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi MensahPhp Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi MensahPHP Barcelona Conference
 
Wamp & LAMP - Installation and Configuration
Wamp & LAMP - Installation and ConfigurationWamp & LAMP - Installation and Configuration
Wamp & LAMP - Installation and ConfigurationChetan Soni
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13DanWooster1
 
APACHE
APACHEAPACHE
APACHEARJUN
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsDECK36
 

Similar to Phalcon 2 - PHP Brazil Conference (20)

Php ppt
Php pptPhp ppt
Php ppt
 
Php through the eyes of a hoster confoo
Php through the eyes of a hoster confooPhp through the eyes of a hoster confoo
Php through the eyes of a hoster confoo
 
Updating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_ServerUpdating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_Server
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Updating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_ServerUpdating_PHP_on_OS_X_Server
Updating_PHP_on_OS_X_Server
 
John's Top PECL Picks
John's Top PECL PicksJohn's Top PECL Picks
John's Top PECL Picks
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real
 
Php Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi MensahPhp Applications with Oracle by Kuassi Mensah
Php Applications with Oracle by Kuassi Mensah
 
Phalcon
PhalconPhalcon
Phalcon
 
Wamp & LAMP - Installation and Configuration
Wamp & LAMP - Installation and ConfigurationWamp & LAMP - Installation and Configuration
Wamp & LAMP - Installation and Configuration
 
Its3 Drupal
Its3 DrupalIts3 Drupal
Its3 Drupal
 
Lumen
LumenLumen
Lumen
 
Its3 Drupal
Its3 DrupalIts3 Drupal
Its3 Drupal
 
php basics
php basicsphp basics
php basics
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
 
APACHE
APACHEAPACHE
APACHE
 
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit SoftwaretestsEffizientere WordPress-Plugin-Entwicklung mit Softwaretests
Effizientere WordPress-Plugin-Entwicklung mit Softwaretests
 
php
phpphp
php
 
php
phpphp
php
 
Php
PhpPhp
Php
 

More from Jackson F. de A. Mafra

PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...
PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...
PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...Jackson F. de A. Mafra
 
Phprs meetup - deploys automatizados com gitlab
Phprs   meetup - deploys automatizados com gitlabPhprs   meetup - deploys automatizados com gitlab
Phprs meetup - deploys automatizados com gitlabJackson F. de A. Mafra
 
O que você precisa saber sobre chatbots
O que você precisa saber sobre chatbotsO que você precisa saber sobre chatbots
O que você precisa saber sobre chatbotsJackson F. de A. Mafra
 
WCPOA2019 - WordPress como um backend de seus aplicativos
WCPOA2019  - WordPress como um backend de seus aplicativosWCPOA2019  - WordPress como um backend de seus aplicativos
WCPOA2019 - WordPress como um backend de seus aplicativosJackson F. de A. Mafra
 
WordPress como um backend de seus aplicativos
WordPress como um backend de seus aplicativosWordPress como um backend de seus aplicativos
WordPress como um backend de seus aplicativosJackson F. de A. Mafra
 
The Ultimate Guide to Development in WordPress
The Ultimate Guide to Development in WordPressThe Ultimate Guide to Development in WordPress
The Ultimate Guide to Development in WordPressJackson F. de A. Mafra
 
Precisamos de um barco maior introdução ao dimensionamento de aplicações
Precisamos de um barco maior introdução ao dimensionamento de aplicaçõesPrecisamos de um barco maior introdução ao dimensionamento de aplicações
Precisamos de um barco maior introdução ao dimensionamento de aplicaçõesJackson F. de A. Mafra
 
Hangout Tempo Real Eventos - ChatOps (ChatBots e DevOps) - Como bots podem ...
Hangout  Tempo Real Eventos - ChatOps (ChatBots e DevOps)  - Como bots podem ...Hangout  Tempo Real Eventos - ChatOps (ChatBots e DevOps)  - Como bots podem ...
Hangout Tempo Real Eventos - ChatOps (ChatBots e DevOps) - Como bots podem ...Jackson F. de A. Mafra
 
Hangout Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...
Hangout  Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...Hangout  Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...
Hangout Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...Jackson F. de A. Mafra
 
Hangout Tempo Real Eventos - Javascript - Os Primeiros Passos
Hangout  Tempo Real Eventos - Javascript - Os Primeiros PassosHangout  Tempo Real Eventos - Javascript - Os Primeiros Passos
Hangout Tempo Real Eventos - Javascript - Os Primeiros PassosJackson F. de A. Mafra
 
Hangout Tempo Real Eventos - Nodejs - Os Primeiros Passos
Hangout  Tempo Real Eventos - Nodejs - Os Primeiros PassosHangout  Tempo Real Eventos - Nodejs - Os Primeiros Passos
Hangout Tempo Real Eventos - Nodejs - Os Primeiros PassosJackson F. de A. Mafra
 
Conexao kinghost - Vendas inteligentes com intelibots
Conexao kinghost - Vendas inteligentes com intelibotsConexao kinghost - Vendas inteligentes com intelibots
Conexao kinghost - Vendas inteligentes com intelibotsJackson F. de A. Mafra
 
TDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit HappensTDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit HappensJackson F. de A. Mafra
 

More from Jackson F. de A. Mafra (20)

PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...
PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...
PHP Conference 2020 - A eterna luta: compatibilidade retroativa vs. dívida té...
 
PHP SSO no Zentyal
PHP SSO no ZentyalPHP SSO no Zentyal
PHP SSO no Zentyal
 
Phprs meetup - deploys automatizados com gitlab
Phprs   meetup - deploys automatizados com gitlabPhprs   meetup - deploys automatizados com gitlab
Phprs meetup - deploys automatizados com gitlab
 
O que você precisa saber sobre chatbots
O que você precisa saber sobre chatbotsO que você precisa saber sobre chatbots
O que você precisa saber sobre chatbots
 
WCPOA2019 - WordPress como um backend de seus aplicativos
WCPOA2019  - WordPress como um backend de seus aplicativosWCPOA2019  - WordPress como um backend de seus aplicativos
WCPOA2019 - WordPress como um backend de seus aplicativos
 
WordPress como um backend de seus aplicativos
WordPress como um backend de seus aplicativosWordPress como um backend de seus aplicativos
WordPress como um backend de seus aplicativos
 
The Ultimate Guide to Development in WordPress
The Ultimate Guide to Development in WordPressThe Ultimate Guide to Development in WordPress
The Ultimate Guide to Development in WordPress
 
Precisamos de um barco maior introdução ao dimensionamento de aplicações
Precisamos de um barco maior introdução ao dimensionamento de aplicaçõesPrecisamos de um barco maior introdução ao dimensionamento de aplicações
Precisamos de um barco maior introdução ao dimensionamento de aplicações
 
Hangout Tempo Real Eventos - ChatOps (ChatBots e DevOps) - Como bots podem ...
Hangout  Tempo Real Eventos - ChatOps (ChatBots e DevOps)  - Como bots podem ...Hangout  Tempo Real Eventos - ChatOps (ChatBots e DevOps)  - Como bots podem ...
Hangout Tempo Real Eventos - ChatOps (ChatBots e DevOps) - Como bots podem ...
 
Hangout Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...
Hangout  Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...Hangout  Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...
Hangout Tempo Real Eventos - Android - Os primeiros passos do desenvolviment...
 
Hangout Tempo Real Eventos - Javascript - Os Primeiros Passos
Hangout  Tempo Real Eventos - Javascript - Os Primeiros PassosHangout  Tempo Real Eventos - Javascript - Os Primeiros Passos
Hangout Tempo Real Eventos - Javascript - Os Primeiros Passos
 
Hangout Tempo Real Eventos - Nodejs - Os Primeiros Passos
Hangout  Tempo Real Eventos - Nodejs - Os Primeiros PassosHangout  Tempo Real Eventos - Nodejs - Os Primeiros Passos
Hangout Tempo Real Eventos - Nodejs - Os Primeiros Passos
 
Desmistificando o DialogFlow
Desmistificando o DialogFlowDesmistificando o DialogFlow
Desmistificando o DialogFlow
 
ChatOps (ChatBots + DevOps)
ChatOps (ChatBots + DevOps) ChatOps (ChatBots + DevOps)
ChatOps (ChatBots + DevOps)
 
Conexao kinghost - Vendas inteligentes com intelibots
Conexao kinghost - Vendas inteligentes com intelibotsConexao kinghost - Vendas inteligentes com intelibots
Conexao kinghost - Vendas inteligentes com intelibots
 
WoMakersCode 2016 - Shit Happens
WoMakersCode 2016 -  Shit HappensWoMakersCode 2016 -  Shit Happens
WoMakersCode 2016 - Shit Happens
 
Dev Heroes
Dev HeroesDev Heroes
Dev Heroes
 
Trilha Android - Android Evolved
Trilha Android - Android EvolvedTrilha Android - Android Evolved
Trilha Android - Android Evolved
 
TDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit HappensTDC 2015 - POA - Trilha PHP - Shit Happens
TDC 2015 - POA - Trilha PHP - Shit Happens
 
Material design
Material designMaterial design
Material design
 

Phalcon 2 - PHP Brazil Conference

  • 3. Why? • Use of frameworks has become mandatory in professional development with PHP • They offer a philosophy and organized structures to easily maintain projects writing less code and making work more fun
  • 4. How PHP works? 1. PHP have dynamic and weak typing discipline 2. PHP is interpreted (not compiled) 3. Every time a script is loaded, should be interpreted by PHP 4. If a bytecode cache (like APC) isn’t used, syntax checking is performed every time
  • 5. How traditional php frameworks works? 1. Many files with classes and functions are read at every request made. Disk reading is expensive in terms of performance 2. Modern frameworks use lazy loading technique (autoload) for load and execute only code needed 3. Continuous loading/interpreting could be expensive and impact your application performance 4. When you use a framework most of the code remain the same across development. Why load and interpret it every time?
  • 6. How a PHP C extension works? 1. C extensions are loaded together with PHP one time, on the web server dispatch process 2. Classes and functions provided by the extension are ready to use for any application 3. The code isn’t interpreted because it is compiled to a specific platform and processor
  • 7. What is Phalcon? Phalcon is an open source, full stack framework for PHP 5 written as a C-extension, optimized for high performance. You don’t need to learn or use the C language, since the functionality is exposed as PHP classes ready for you to use. Phalcon also is loosely coupled, allowing you to use its objects as glue components based on the needs of your application.
  • 8. How Phalcon works? 1. Components are loosely coupled. You may use the components you want without depending on a full stack 2. Low-level optimizations provide the lowest overhead for MVC-based applications 3. Interact with databases with maximum performance by using a C-language ORM for PHP 4. Phalcon is directly engaged with PHP, so it can directly access internal structures optimizing execution as well
  • 10. Compare how Phalcon is faster than other frameworks Traditional Frameworks Phalcon Interpretation of hundreds or thousands of PHP lines on each request YES NO Load dozens of files in each request YES NO Checking the existence of functions, methods, classes, constants at each request YES NO Low-level optimizations gaining microseconds for each request NO YES
  • 13. Test Environment Operative System: Mac OS X Snow Leopard 10.6.8 • Web Server: Apache httpd 2.2.21 • PHP: 5.3.8 + APC 3.1.9 (Without Xdebug) • CPU: 3.06 Ghz Intel Core 2 Duo • Main Memory: 4GB 1067 MHz DDR3 • Hard Disk: 500GB SCSI/SAS HDD
  • 14. Framework Benchmark ab -n 1000 -c 5 http://localhost/bench/phalcon
  • 17. Number of Interpreted Files per Request
  • 20. Installation To use phalcon on Windows you can download a DLL library. Edit your php.ini file and then append at the end: extension=php_phalcon.dll Restart your webserver.
  • 21. Requirements Prerequisite packages are: PHP >= 5.3 development resources GCC compiler (Linux/Solaris) Git (if not already installed in your system - unless you download the package from GitHub and upload it on your server via FTP/SFTP)
  • 22. Requirements Specific packages for common platforms: #Ubuntu sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql #Suse sudo yast -i gcc make autoconf2.13 php5-devel php5-pear php5-mysql #CentOS/RedHat/Fedora sudo yum install php-devel pcre-devel gcc make #Solaris pkg install gcc-45 php-53 apache-php53
  • 23. Compilation git clone --depth=1 git://github.com/phalcon/cphalcon.git cd cphalcon/build sudo ./install
  • 24. Configure Add extension to your php configuration: #Suse: Add this line in your php.ini extension=phalcon.so #Centos/RedHat/Fedora: Add a file called phalcon.ini in /etc/php.d/ with this content: extension=phalcon.so #Ubuntu/Debian: Add a file called 30-phalcon.ini in /etc/php.d/ with this content: extension=phalcon.so #Debian with php5-fpm: Add a file called 30-phalcon.ini in /etc/php5/fpm/conf.d/30-phalcon.ini with this content: extension=phalcon.so Restart the webserver.
  • 25. Configure Phalcon automatically detects your architecture, however, you can force the compilation for a specific architecture: cd cphalon/build sudo ./install 32bits sudo ./install 64bits sudo ./install safe
  • 26. Mac OS X On a Mac OS X system you can compile and install the extension from the source code: Requirements Prerequisite packages are: PHP >= 5.3 development resources XCode #brew brew tap homebrew/homebrew-php brew install php53-phalcon brew install php54-phalcon brew install php55-phalcon brew install php56-phalcon #MacPorts sudo port install php53-phalcon sudo port install php54-phalcon sudo port install php55-phalcon sudo port install php56-phalcon
  • 27. Installation on XAMPP XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. Once you download XAMPP, all you have to do is extract it and start using it. Below are detailed instructions on how to install Phalcon on XAMPP for Windows. Using the latest XAMPP version is highly recommended.
  • 28. Installation on XAMPP XAMPP is always releasing 32 bit versions of Apache and PHP. You will need to download the x86 version of Phalcon for Windows from the download section. After downloading the Phalcon library you will have a zip file like the one shown below:
  • 29. Installation on XAMPP Extract the library from the archive to get the Phalcon DLL:
  • 30. Installation on XAMPP Copy the file php_phalcon.dll to the PHP extensions. If you have installed XAMPP in the c:xampp folder, the extension needs to be in c:xamppphpext
  • 31. Installation on XAMPP Edit the php.ini file, it is located at C:xamppphpphp.ini. It can be edited with Notepad or a similar program. We recommend Notepad++ to avoid issues with line endings. Append at the end of the file: extension=php_phalcon.dll and save it.
  • 32. Installation on XAMPP Restart the Apache Web Server from the XAMPP Control Center. This will load the new PHP configuration.
  • 33. Installation on XAMPP Open your browser to navigate to http://localhost. The XAMPP welcome page will appear. Click on the link phpinfo(). phpinfo() will output a significant amount of information on screen about the current state of PHP. Scroll down to check if the phalcon extension has been loaded correctly. If you can see the phalcon version in the phpinfo() output, congrats!, You are now flying with Phalcon.
  • 34. Creating a project File structure Phalcon does not impose a particular file structure for application development. Due to the fact that it is loosely coupled, you can implement Phalcon powered applications with a file structure you are most comfortable using.
  • 35. Creating a project For the purposes of this tutorial and as a starting point, we suggest the following structure: lab01/ app/ controllers/ models/ views/ public/ css/ img/ js/
  • 36. Beautiful URLs #/tutorial/.htaccess <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ public/ [L] RewriteRule (.*) public/$1 [L] </IfModule> #/tutorial/.htaccess <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^$ public/ [L] RewriteRule (.*) public/$1 [L] </IfModule>
  • 37. Bootstrap <?php try { //Register an autoloader $loader = new PhalconLoader(); $loader->registerDirs(array( '../app/controllers/', '../app/models/' ))->register(); //Create a DI $di = new PhalconDIFactoryDefault(); //Setup the view component $di->set('view', function(){ $view = new PhalconMvcView(); $view->setViewsDir('../app/views/'); return $view; }); //Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function(){ $url = new PhalconMvcUrl(); $url->setBaseUri('/lab01//'); return $url; }); //Handle the request $application = new PhalconMvcApplication($di); echo $application->handle()->getContent(); } catch(PhalconException $e) { echo "PhalconException: ", $e->getMessage(); }
  • 38. Creating a Controller By default Phalcon will look for a controller named “Index”. It is the starting point when no controller or action has been passed in the request. The index controller (app/controllers/IndexController.php) looks like: <?php class IndexController extends PhalconMvcController { public function indexAction() { echo "<h1>Hello!</h1>"; } }
  • 39. Creating a Controller In our case (app/views/index/index.phtml): <?php echo "<h1>Hello!</h1>"; Our controller (app/controllers/IndexController.php) now has an empty action definition: <?php class IndexController extends PhalconMvcController { public function indexAction() { } }
  • 40. Creating a Model Phalcon brings the first ORM for PHP entirely written in C-language. Instead of increasing the complexity of development, it simplifies it. Before creating our first model, we need to create a database table outside of Phalcon to map it to. A simple table to store registered users can be defined like this: CREATE TABLE `users` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(70) NOT NULL, `email` varchar(70) NOT NULL, PRIMARY KEY (`id`) );
  • 41. Creating a Model A model should be located in the app/models directory (app/models/Users.php). The model maps to the “users” table: <?php class Users extends PhalconMvcModel { }
  • 42. Setting a Database Connection In order to be able to use a database connection and subsequently access data through our models, we need to specify it in our bootstrap process. A database connection is just another service that our application has that can be used for several components:
  • 43. Setting a Database Connection <?php try { //Register an autoloader $loader = new PhalconLoader(); $loader->registerDirs(array( '../app/controllers/', '../app/models/' ))->register(); //Create a DI $di = new PhalconDIFactoryDefault(); / /Setup the database service $di->set('db', function(){ return new PhalconDbAdapterPdoMysql(array( "host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "test_db" )); }); //Setup the view component $di->set('view', function(){ $view = new PhalconMvcView(); $view->setViewsDir('../app/views/'); return $view; }); //Setup a base URI so that all generated URIs include the "tutorial" folder $di->set('url', function(){ $url = new PhalconMvcUrl(); $url->setBaseUri('/tutorial/'); return $url; }); //Handle the request $application = new PhalconMvcApplication($di); echo $application->handle()->getContent(); } catch(Exception $e) { echo "PhalconException: ", $e->getMessage(); }
  • 44. Volt: Template Engine Volt is an ultra-fast and designer friendly templating language written in C for PHP. It provides you a set of helpers to write views in an easy way. Volt is highly integrated with other components of Phalcon, just as you can use it as a stand-alone component in your applications.
  • 46. Volt: Template Engine Volt views are compiled to pure PHP code, so basically they save the effort of writing PHP code manually: {# app/views/products/show.volt #}{% block last_products %}{% for product in products %} * Name: {{ product.name|e }} {% if product.status == "Active" %} Price: {{ product.price + product.taxes/100 }} {% endif %}{% endfor %}{% endblock %}
  • 47. Phalcon Query Language (PHQL) Phalcon Query Language, PhalconQL or simply PHQL is a high-level, object-oriented SQL dialect that allows to write queries using a standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS.
  • 48. Phalcon Query Language (PHQL) In PHQL, we’ve implemented a set of features to make your access to databases more secure: • Bound parameters are part of the PHQL language helping you to secure your code • PHQL only allows one SQL statement to be executed per call preventing injections • PHQL ignores all SQL comments which are often used in SQL injections • PHQL only allows data manipulation statements, avoiding altering or dropping tables/databases by mistake or externally without authorization • PHQL implements a high-level abstraction allowing you to handle tables as models and fields as class attributes
  • 49. Phalcon Query Language (PHQL) Creating PHQL Queries PHQL queries can be created just by instantiating the class PhalconMvcModelQuery: <?php // Instantiate the Query $query = new PhalconMvcModelQuery("SELECT * FROM Cars", $this->getDI()); // Execute the query returning a result if any $cars = $query->execute();
  • 50. Phalcon Query Language (PHQL) Selecting Records As the familiar SQL, PHQL allows querying of records using the SELECT statement we know, except that instead of specifying tables, we use the models classes: <?php $query = $manager->createQuery("SELECT * FROM Cars ORDER BY Cars.name"); $query = $manager->createQuery("SELECT Cars.name FROM Cars ORDER BY Cars.name")
  • 51. Phalcon Query Language (PHQL) Result Types Depending on the type of columns we query, the result type will vary. If you retrieve a single whole object, then the object returned is a PhalconMvcModelResultsetSimple. This kind of resultset is a set of complete model objects: <?php $phql = "SELECT c.* FROM Cars AS c ORDER BY c.name"; $cars = $manager->executeQuery($phql); foreach ($cars as $car) { echo "Name: ", $car->name, "n"; }
  • 52. Phalcon Query Language (PHQL) Result Types Or: <?php $cars = Cars::find(array("order" => "name")); foreach ($cars as $car) { echo "Name: ", $car->name, "n"; }
  • 53. Phalcon Query Language (PHQL) Inserting Data Phalcon doesn’t only transform the PHQL statements into SQL. All events and business rules defined in the model are executed as if we created individual objects manually. Let’s add a business rule on the model cars. A car cannot cost less than $ 10,000:
  • 54. Phalcon Query Language (PHQL) Inserting Data <?php use PhalconMvcModelMessage; class Cars extends PhalconMvcModel { public function beforeCreate() { if ($this->price < 10000) { $this->appendMessage(new Message("A car cannot cost less than $ 10,000")); return false; } } }
  • 55. Phalcon Query Language (PHQL) Inserting Data If we made the following INSERT in the models Cars, the operation will not be successful because the price does not meet the business rule that we implemented: <?php $phql = "INSERT INTO Cars VALUES (NULL, ’Nissan Versa’, 7, 9999.00, 2012, ’Sedan’)"; $result = $manager->executeQuery($phql); if ($result->success() == false) { foreach ($result->getMessages() as $message) { echo $message->getMessage(); } }
  • 56. Phalcon Query Language (PHQL) Updating Data Updating rows is very similar than inserting rows. As you may know, the instruction to update records is UPDATE. When a record is updated the events related to the update operation will be executed for each row.
  • 57. Phalcon Query Language (PHQL) Updating Data <?php // Updating a single column $phql = "UPDATE Cars SET price = 15000.00 WHERE id = 101"; $manager->executeQuery($phql); // Updating multiples columns $phql = "UPDATE Cars SET price = 15000.00, type = ’Sedan’ WHERE id = 101"; $manager->executeQuery($phql);
  • 58. Phalcon Query Language (PHQL) Updating Data <?php // Using placeholders $phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2"; $manager->executeQuery($phql, array( 0 => 7000.00, 1 => ’Sedan’, 2 => 5 ));
  • 59. Phalcon Query Language (PHQL) Updating Data An UPDATE statement performs the update in two phases: • First, if the UPDATE has a WHERE clause it retrieves all the objects that match these criteria, • Second, based on the queried objects it updates/changes the requested attributes storing them to the relational database
  • 60. Phalcon Query Language (PHQL) Deleting Data When a record is deleted the events related to the delete operation will be executed for each row: <?php // Deleting a single row $phql = "DELETE FROM Cars WHERE id = 101"; $manager->executeQuery($phql); // Deleting multiple rows $phql = "DELETE FROM Cars WHERE id > 100"; $manager->executeQuery($phql);
  • 61. Phalcon Query Language (PHQL) Deleting Data When a record is deleted the events related to the delete operation will be executed for each row: <?php // Using placeholders $phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:"; $manager->executeQuery( $phql, array( ’initial’ => 1, ’final’ => 100 ) );
  • 62. Phalcon Query Language (PHQL) Deleting Data DELETE operations are also executed in two phases like UPDATEs.
  • 63. Phalcon Query Language (PHQL) Creating queries using the Query Builder //Getting a whole set $robots = $this->modelsManager->createBuilder() ->from(’Robots’) ->join(’RobotsParts’) ->orderBy(’Robots.name’) ->getQuery() ->execute();
  • 64. Phalcon Query Language (PHQL) Creating queries using the Query Builder //Getting the first row $robots = $this->modelsManager->createBuilder() ->from(’Robots’) ->join(’RobotsParts’) ->orderBy(’Robots.name’) ->getQuery() ->getSingleResult();
  • 65. Phalcon Query Language (PHQL) PHQL Lifecycle Being a high-level language, PHQL gives developers the ability to personalize and customize different aspects in order to suit their needs. The following is the life cycle of each PHQL statement executed: • The PHQL is parsed and converted into an Intermediate Representation (IR) which is independent of the SQL implemented by database system • The IR is converted to valid SQL according to the database system associated to the model • PHQL statements are parsed once and cached in memory. Further executions of the same statement result in a slightly faster execution
  • 66. Routing The router component allows defining routes that are mapped to controllers or handlers that should receive the request. A router simply parses a URI to determine this information. The router has two modes: MVC mode and match-only mode. The first mode is ideal for working with MVC applications.
  • 67. Routing Defining Routes PhalconMvcRouter provides advanced routing capabilities. In MVC mode, you can define routes and map them to controllers/actions that you require. A route is defined as follows:
  • 68. Routing An application can have many paths, define routes one by one can be a cumbersome task. In these cases we can create more flexible routes: <?php // Create the router $router = new PhalconMvcRouter(); //Define a route $router->add( "/admin/:controller/a/:action/:params", array( "controller" => 1, "action" => 2, "params" => 3, ) );
  • 69. Routing Parameters with Names The example below demonstrates how to define names to route parameters: <?php $router->add( "/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params", array( "controller" => "posts", "action" => "show", "year" => 1, // ([0-9]{4}) "month" => 2, // ([0-9]{2}) "day" => 3, // ([0-9]{2}) "params" => 4, // :params ) );
  • 70. Routing HTTP Method Restrictions When you add a route using simply add(), the route will be enabled for any HTTP method. Sometimes we can restrict a route to a specific method, this is especially useful when creating RESTful applications: <?php // This route only will be matched if the HTTP method is GET $router->addGet("/products/edit/{id}", "Products::edit"); // This route only will be matched if the HTTP method is POST $router->addPost("/products/save", "Products::save"); // This route will be matched if the HTTP method is POST or PUT $router->add("/products/update")->via(array("POST", "PUT"));
  • 71. Routing Not Found Paths If none of the routes specified in the router are matched, you can define a group of paths to be used in this scenario: <?php //Set 404 paths $router->notFound(array( "controller" => "index", "action" => "route404" ));
  • 72. DRY or DIE Don't Repeat Yourself (DRY) or Duplication is Evil (DIE) is a principle of software development
  • 73. KISS KISS is an acronym for the design principle "Keep it simple, Stupid!".
  • 74. SOLID The principles when applied together intends to make it more likely that a programmer will create a system that is easy to maintain and extend over time
  • 75. SOCKETS Ratchet - WebSockets for PHP Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directional applications between clients and servers over WebSockets. http://socketo.me/
  • 76. Background Jobs Setup background jobs with Phalcon and Resque https://github.com/doshimehul/phalcon-resque
  • 77. RESTful Phalcon REST provides a framework to build your own API upon, core functionalities include: • Response formatting using Fractal's Transformer concept (I got this concept from a book written by Phil Sturgeon) • Authentication sessions using Json Web Token • Access Control List using ACL class Phalcon provides • Username and password authentication service • Google authentication service • Documentation generator based on docblock annotations http://phalconist.com/olivierandriessen/phalcon-rest
  • 78. RESTful What is Fractal? Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON. Think of this as a view layer for your JSON/YAML/etc. When building an API it is common for people to just grab stuff from the database and pass it to json_encode(). http://fractal.thephpleague.com/
  • 79. Phalcon Micro-Start Phalcon Micro-Start A more practical example of the start of a Phalcon micro application What's Included? Basic page example Partial views (Simple view engine) URL with params JSON return Cached view Redirect URL https://github.com/james2doyle/phalcon-micro-start
  • 80. Phalcon Docker Docker Phalcon Apache2 Docker image based on Ubuntu 14.04 (trusty) with the latest stable Phalcon PHP Framework with apache 2.4 webserver installed. https://github.com/szeist/docker-phalcon-apache2
  • 81. Vagrant Create and configure lightweight, reproducible, and portable development environments. Vagrant will change how you work http://www.vagrantup.com/
  • 82. Puppet Puppet is IT automation software that helps system administrators manage infrastructure throughout its lifecycle, from provisioning and configuration to orchestration and reporting. Using Puppet, you can easily automate repetitive tasks, quickly deploy critical applications, and proactively manage change, scaling from 10s of servers to 1000s, on-premise or in the cloud. http://puppetlabs.com/puppet/what-is-puppet
  • 83. PuPHPet PuPHPet, an excellent GUI tool providing a simple wizard, which creates a Puppet-powered Vagrant configuration, usable immediately.Originally started by Juan Treminio, PuPHPet makes creating environments perfectly tailored for PHP developers on stacks such as {W,M,L}AMP dead simple. https://puphpet.com/
  • 84. Provisioning Phalcon PuPHPet is an absolutely awesome tool in getting up and running with a development environment really fast, and offers some very neat default options. But what if we want to step outside the defaults? What if we'd, for example, like to install a PHP extension that isn't part of the default distribution and doesn't exist in package managers? http://docs.vagrantup.com/v2/provisioning/index.html
  • 85. Phalconist Resources catalog for Phalcon framework http://phalconist.com/