PSR-2
while for Zephir code, we have an .editorconfig
file available at the root of the repository to help you follow the standards.master
branch#12345 - Create New Object
4.0.x
branchT12345-create-new-object
.git/hooks
commit-msg
and paste the code below in it and save it :#!/bin/bash
# This Way You can Customize Which Branches Should be Skipped When
# Prepending Commit Message.
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(master develop)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
BRANCH_NAME="${BRANCH_NAME##*/}"
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
BRANCH_IN_COMMIT=$(grep -c "\[$BRANCH_NAME\]" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ $BRANCH_EXCLUDED -eq 1 ]] && ! [[ $BRANCH_IN_COMMIT -ge 1 ]]; then
ISSUE="$(echo $BRANCH_NAME | cut -d'-' -f 1)"
ISSUE="${ISSUE/T/#}"
sed -i.bak -e "1s/^/[$ISSUE] - /" $1
fi
chmod a+x commit-msg
12345
issue.Devilbox
is a modern and highly customizable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts, SSL certificates and DNS records are created automatically. Reverse proxies per project are supported to ensure listening server such as NodeJS can also be reached. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is already pre-setup.Project name | my-phalcon |
---|---|
VirtualHost directory | /shared/httpd/my-phalcon |
Database | n.a. |
TLD_SUFFIX |
loc |
Project URL | http://my-phalcon.loc , https://my-phalcon.loc |
Nanobox
is a portable, micro platform for developing and deploying apps. When working locally, Nanobox uses Docker to spin up and configure a virtual development environment configured to your specific needs. When you’re ready to deploy to live servers, Nanobox will take that same environment and spin it up on your cloud provider of choice, where you can then manage and scale your app through the Nanobox dashboard.mkdir nanobox-phalcon && cd nanobox-phalcon
find()
findFirst()
query()
findFirstBy
etc.Phalcon\Db\Adapter\Pdo\Mysql : Mysql
Phalcon\Db\Adapter\Pdo\Postgresql : Postgresql
Phalcon\Db\Adapter\Pdo\Sqlite : Sqlite
Zephir
stands for Ze(nd Engine) Ph(p) I(nt)r(mediate)
. It is a high level language. It is used for creation and maintainability of extensions for PHP. It exported to C code that can be compiled and optimized by major C compilers such as gcc/clang/vc++
. Event Name | Triggered |
---|---|
boot | Executed when the application handles its first request |
beforeStartModule | Before initialize a module, only when modules are registered |
afterStartModule | After initialize a module, only when modules are registered |
beforeHandleRequest | Before execute the dispatch loop |
afterHandleRequest | After execute the dispatch loop |
setVar()
method.$this->view->setVar("username", $user->username);
Phalcon\Loader
is an autoloader that implements PSR-4. Just like any autoloader, depending on its setup, it will try and find the files your code is looking for based on file, class, namespace etc. Since this component is written in C, it offers the lowest overhead when processing its setup, thus offering a performance boost.spl_autoload_register()
to register a custom autoloader for our application. Phalcon\Loader
hides this complexity. After you define all your namespaces, classes, directories and files you will need to call the register()
function, and the autoloader is ready to be used.<?php
use Phalcon\Loader;
$loader = new Loader();
$loader->registerNamespaces(
[
'MyApp' => 'app/library',
'MyApp\Models' => 'app/models',
]
);
$loader->register();
register()
uses spl_autoload_register()
internally. As a result it accepts also accepts the boolean prepend parameter. If supplied and is true, the autoloader will be prepended on the autoload queue instead of appended (default behavior).isRegistered()
method to check if your autoloader is registered or not.composer global require phalcon/devtools
composer require phalcon/devtools
$ phalcon
Phalcon DevTools (4.0.0)
Available commands:
info (alias of: i)
commands (alias of: list, enumerate)
controller (alias of: create-controller)
module (alias of: create-module)
model (alias of: create-model)
all-models (alias of: create-all-models)
project (alias of: create-project)
scaffold (alias of: create-scaffold)
migration (alias of: create-migration)
webtools (alias of: create-webtools)
serve (alias of: server)
console (alias of: shell, psysh)
Endpoint | Description |
---|---|
/login |
Path /session/login . Presents the login screen |
/logout |
Path /session/logout . Logs user out, redirects to /login |
/portal/invoices/list |
List invoices for the currently logged in customer |
/portal/invoices/view/{0-9} |
View invoice for the currently logged in customer |
/portal/invoices/pay/{0-9} |
Pay invoice (payment gateway) |
/portal/reports/list |
List available reports for the logged in customer |
/portal/reports/view/{0-9} |
View report for this customer |
/accounting/invoices/add |
Add new invoice |
/accounting/invoices/edit/{0-9} |
Edit an invoice |
/accounting/invoices/view/{0-9} |
View an invoice |
/accounting/invoices/list |
List all invoices |
/accounting/invoices/void/{0-9} |
Void an invoice |
/admin/cache/view |
View all cache items |
/admin/cache/delete/{0-9} |
Delete a cache item |
/admin/cache/void |
Void the whole cache |
/admin/permissions/list |
Show the current permissions |
/admin/permissions/add |
Add a new permission |
/admin/permissions/edit/{0-9} |
Edit a permission |
/admin/products/list |
List all products |
/admin/products/add |
Add a product |
/admin/products/edit/{0-9} |
Edit a product |
/admin/products/delete/{0-9} |
Delete a product |
/admin/products/view/{0-9} |
View a product |
/admin/users/list |
List all users |
/admin/users/add |
Add a user |
/admin/users/edit/{0-9} |
Edit a user |
/admin/users/delete/{0-9} |
Delete a user |
/admin/users/view/{0-9} |
View a user |
Phalcon\Di
is a container that stores services or components (classes). These services are available throughout the application and ease development. Let us assume we are developing a component called InvoiceComponent that performs some calculations for a customer’s invoice. It requires a database connection to retrieve the Invoice record from the database.<?php
use Phalcon\Db\Adapter\Mysql;
class InvoiceComponent
{
public function calculate()
{
$connection = new Mysql(
[
'host' => 'localhost',
'username' => 'root',
'password' => 'secret',
'dbname' => 'tutorial',
]
);
$invoice = $connection->exec(
'SELECT * FROM Invoices WHERE inv_id = 1'
);
// ...
}
}
$invoice = new InvoiceComponent();
$invoice->calculate();
CLI application
in Phalcon, using the Phalcon\Cli\Console
class. This class extends from the main abstract application class, and uses a directory in which the Task scripts are located. Task scripts are classes that extend Phalcon\Cli\Task
and contain the code that we need executed.src/tasks/MainTask.php
php cli.php
cli.php
is the entry point of our application, while the src/tasks directory contains all the task classes that handle each command.Phalcon\Cache
namespace offers a Cache component, that implements the PSR-16 interface, making it compatible with any component that requires that interface for its cache.processed/calculated
data, can be stored in a cache storage for easier and faster retrieval. Since Phalcon\Cache
components are written in Zephir, and therefore compiled as C code, they can achieve higher performance, while reducing the overhead that comes with getting data from any storage container. Some examples that warrant the use of cache are :Phalcon\Cache
components rely on Phalcon\Storage
components. Phalcon\Storage
is split into two categories : Serializers and Adapters.Phalcon\Cache
component, you will need to pass a Phalcon\Cache\Adapter\*
class in it or one that implements the Phalcon\Cache\Adapter\AdapterInterface
. For a detailed explanation on adapters and serializers, see below.<?php
use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\SerializerFactory;
$serializerFactory = new SerializerFactory();
$adapterFactory = new AdapterFactory($serializerFactory);
$options = [
'defaultSerializer' => 'Json',
'lifetime' => 7200
];
$adapter = $adapterFactory->newInstance('apcu', $options);
$cache = new Cache($adapter);
sufficient/appropriate
. Phalcon\Escaper
provides contextual escaping and is written in Zephir, providing the minimal overhead when escaping different kinds of texts.<?php
use Phalcon\Escaper;
$escaper = new Escaper();
$title = '</title><script>alert(1)</script>';
echo $escaper->escapeHtml($title);
// </title><script>alert(1)</script>
$css = ';`(';
echo $escaper->escapeCss($css);
// < / style>
$fontName = 'Verdana\"</style>';
echo $escaper->escapeCss($fontName);
// Verdana\22 \3c \2f style\3e
$js = "';</script>Hello";
echo $escaper->escapeJs($js);
// \x27\x3b\x3c\2fscript\x3eHello
Phalcon\Logger
is a component providing logging services for applications. It offers logging to different back-ends using different adapters. It also offers transaction logging, configuration options and different logging formats. You can use the Phalcon\Logger
for any logging need your application has, from debugging processes to tracing application flow.Phalcon\Logger
has been rewritten to comply with PSR-3. This allows you to use the Phalcon\Logger
to any application that utilizes a PSR-3 logger
, not just Phalcon based ones.Adapter | Description |
---|---|
Phalcon\Logger\Adapter\Noop | Blackhole adapter (used for testing mostly) |
Phalcon\Logger\Adapter\Stream | Logs messages on a file stream |
Phalcon\Logger\Adapter\Syslog | Logs messages to the Syslog |
<?php
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;
class Invoices extends Model
{
/**
* @var int
*/
public $inv_id;
/**
* @var string
*/
public $inv_created_at;
/**
* @var int
*/
public $inv_status_flag;
/**
* @var string
*/
public $inv_title;
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
'beforeCreate' => [
'field' => 'inv_created_at',
'format' => 'Y-m-d',
],
]
)
);
}
}
Phalcon\Mvc\Router
component allows you to define routes that are mapped to controllers or handlers that receive and can handle the request. The router has two modes: MVC mode and match-only mode. The first mode is ideal for working with MVC applications.<?php
use Phalcon\Mvc\Router;
$router = new Router();
$router->add(
'/admin/invoices/list',
[
'controller' => 'invoices',
'action' => 'list',
]
);
$router->handle(
$_SERVER["REQUEST_URI"]
);
Phalcon\Mvc\Router
component that are used to define the position of the route in the processing stack.POSITION_FIRST
POSITION_LAST
public function __construct(
bool $defaultRoutes = true
)
public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null,
mixed $position = Router::POSITION_LAST
): RouteInterface
Phalcon\Session\Manager
is an object oriented approach to handle sessions using Phalcon. There are several reasons to use this component instead of raw sessions or accessing the $_SESSION
superglobal: Phalcon\Session\Manager
is a component that allows you to manipulate sessions in your application. This manager accepts an adapter which is the way the data will be communicated to a particular store.<?php
use Phalcon\Session\Manager;
use Phalcon\Session\Adapter\Stream;
$session = new Manager();
$files = new Stream(
[
'savePath' => '/tmp',
]
);
$session->setAdapter($files);
Phalcon\Validation
is an independent validation component that validates an arbitrary set of data. This component can be used to implement validation rules on data objects that do not belong to a model or collection.<?php
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
'name',
new PresenceOf(
[
'message' => 'The name is required',
]
)
);
$validation->add(
'email',
new PresenceOf(
[
'message' => 'The e-mail is required',
]
)
);
$validation->add(
'email',
new Email(
[
'message' => 'The e-mail is not valid',
]
)
);
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}
Phalcon\Mvc\Dispatcher
is the component responsible for instantiating controllers and executing the required actions on them in an MVC application. Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.<?php
use Phalcon\Di;
use Phalcon\Mvc\Dispatcher;
$container = new Di();
$dispatcher = new Dispatcher();
$dispatcher->setDI($container);
$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$controller = $dispatcher->dispatch();
Phalcon\Http\Request
is a component that encapsulates the actual HTTP request (usually originated by a browser) and sent to our application. The Phalcon\Http\Request
object is a simple value object that is passed between the dispatcher and controller classes, wrapping the HTTP request environment. It also offers easy access to information such as header data, files, method, variables etc.<?php
use Phalcon\Http\Request;
$request = new Request();
// POST
if (true === $request->isPost()) {
// AJAX
if (true === $request->isAjax()) {
// ....
}
}
$_GET
, $_POST
and $_REQUEST
depending on the type of the request. These arrays contain the values present in forms submitted or the parameters sent via the URL. The variables in the arrays are never sanitized and can contain illegal characters or even malicious code, which can lead to SQL injection or Cross Site Scripting (XSS) attacks.Phalcon\Http\Request
allows you to access the values stored in the $_GET
, $_POST
and $_REQUEST
arrays and sanitize or filter them with the filter service.<?php
use Phalcon\Http\Request;
$request = new Request();
$request->get(
$name = null, // string
$filters = null, // mixed
$defaultValue = null, // mixed
$notAllowEmpty = false, // bool
$noRecursive = false // bool
): mixed​
Phalcon\Http\Response
is a component that encapsulates the actual HTTP response by the application to the user. The most commonly returned payload is headers and content. Note that this is not only the actual response payload. The component acts as a constructor of the response and as a HTTP client to send the response back to the caller. You can always use the Phalcon\Http\Message\Response for a PSR-7 compatible response and use a client such as Guzzle to send it back to the caller.<?php
use Phalcon\Http\Response;
// Getting a response instance
$response = new Response();
$response->setStatusCode(404, 'Not Found');
$response->setContent("Sorry, the page doesn't exist");
$response->send();
Phalcon\Http\ResponseInterface
, Phalcon\Di\InjectionAware
and Phalcon\Events\EventsAware
interfaces.<?php
use Phalcon\Http\Response;
// Getting a response instance
$response = new Response(
"Sorry, the page doesn't exist",
404,
'Not Found'
);
$response->send();
Phalcon\Http\Response
offers a collection to store and manipulate cookies. You can then send those cookies back with the response.Phalcon\Http\Response\Cookies
object or any object that implements the Phalcon\Http\Response\CookiesInterface
.<?php
use Phalcon\Http\Response;
use Phalcon\Http\Response\Cookies;
$response = new Response();
$cookies = new Cookies();
$response->setCookies($cookies);
getCookies()
method on the Phalcon\Http\Response
object. The method returns a Phalcon\Http\Response\Cookies
collection object. You can set the cookies in the response object using the setCookies()
, as shown above, and then use sendCookies()
to send them back to the caller.Phalcon\Crypt component
. This class offers simple object-oriented wrappers to the openssl PHP’s encryption library.AES-256-CFB
cipher.AES-256
is used among other places in SSL/TLS across the Internet. It’s considered among the top ciphers. In theory it’s not crackable since the combinations of keys are massive. Although NSA has categorized this in Suite B, they have also recommended using higher than 128-bit keys for encryption.<?php
use Phalcon\Crypt;
$key = "12345"; // Your luggage combination
$crypt = new Crypt();
$text = 'This is the text that you want to encrypt.';
$encrypted = $crypt->encrypt($text, $key);
echo $crypt->decrypt($encrypted, $key);
Phalcon\Security\JWT
is a namespace that contains components that allow you to issue, parse and validate JSON Web Tokens as described in RFC 7519. These components are:<?php
use Phalcon\Security\JWT\Builder;
use Phalcon\Security\JWT\Signer\Hmac;
use Phalcon\Security\JWT\Token\Parser;
use Phalcon\Security\JWT\Validator;
// Defaults to 'sha512'
$signer = new Hmac();
// Builder object
$builder = new Builder($signer);
$now = new DateTimeImmutable();
$issued = $now->getTimestamp();
$notBefore = $now->modify('-1 minute')->getTimestamp();
$expires = $now->modify('+1 day')->getTimestamp();
$passphrase = 'QcMpZ&b&mo3TPsPk668J6QH8JA$&U&m2';
// Setup
$builder
->setAudience('https://target.phalcon.io') // aud
->setContentType('application/json') // cty - header
->setExpirationTime($expires) // exp
->setId('abcd123456789') // JTI id
->setIssuedAt($issued) // iat
->setIssuer('https://phalcon.io') // iss
->setNotBefore($notBefore) // nbf
->setSubject('my subject for this claim') // sub
->setPassphrase($passphrase) // password
;
// Phalcon\Security\JWT\Token\Token object
$tokenObject = $builder->getToken();
// The token
echo $tokenObject->getToken();
// Token split into different lines for readability
//
// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImN0eSI6ImFwcGxpY2F0aW9uXC9qc29uIn0.
// eyJhdWQiOlsiaHR0cHM6XC9cL3RhcmdldC5waGFsY29uLmlvIl0sImV4cCI6MTYxNDE4NTkxN
// ywianRpIjoiYWJjZDEyMzQ1Njc4OSIsImlhdCI6MTYxNDA5OTUxNywiaXNzIjoiaHR0cHM6XC
// 9cL3BoYWxjb24uaW8iLCJuYmYiOjE2MTQwOTk0NTcsInN1YiI6Im15IHN1YmplY3QgZm9yIHR
// oaXMgY2xhaW0ifQ.
// LdYevRZaQDZ2lul4CCQ5DymeP2ubcapTtgeezOZGIq7Meu7rFF1pv32b-AMWOxCS63CQz_jpm
// BPlPyOeEAkMbg
// $tokenReceived is what we received
$tokenReceived = getMyTokenFromTheApplication();
$audience = 'https://target.phalcon.io';
$now = new DateTimeImmutable();
$issued = $now->getTimestamp();
$notBefore = $now->modify('-1 minute')->getTimestamp();
$expires = $now->getTimestamp();
$id = 'abcd123456789';
$issuer = 'https://phalcon.io';
// Defaults to 'sha512'
$signer = new Hmac();
$passphrase = 'QcMpZ&b&mo3TPsPk668J6QH8JA$&U&m2';
// Parse the token
$parser = new Parser();
// Phalcon\Security\JWT\Token\Token object
$tokenObject = $parser->parse($tokenReceived);
// Phalcon\Security\JWT\Validator object
$validator = new Validator($tokenObject, 100); // allow for a time shift of 100
// Throw exceptions if those do not validate
$validator
->validateAudience($audience)
->validateExpiration($expires)
->validateId($id)
->validateIssuedAt($issued)
->validateIssuer($issuer)
->validateNotBefore($notBefore)
->validateSignature($signer, $passphrase)
;
Creating session: $this->session->set("user-name", "Ramana");
Reading or Retriving session: $this->session->get("user-name");
Deleting or Removing session: $this->session->remove("user-name");
Framework | Yii | Laravel | Phalcon |
---|---|---|---|
Type of Project | It helps to creating large projects | It is used to create Web application. | It is used to design variety of projects. |
Database support | It supports relational and non relational db | It supports relational DB. | It supports both relational and non relational db |
Language | It is purely written in PHP | It is written in PHP and follow MVC pattern. | It is written in PHP and C language. |
Scalability | It is quit scalable. | Scalability is high | Good for medium projects. |
Performance | Comparatively low | High but less in compare to Phalcon | High Performance |
.volt
and .phtml
that are given below in table :.volt | .phtml |
---|---|
It is used when the template engine set up. | It is used when the template engine is PHP itself. |
It can be used as a stand-alone component. | It cannot be used as a stand-alone component. |
Volt views are compiled to PHP code. | It includes PHP volt so there is no need of compilation in Phalcon framework. |
Phalcon\Http\Message\Request
is an implementation of the PSR-7 HTTP
messaging interface as defined by PHP-FIG.$httpClient
is the client of your choice which implements PSR-7.<?php
use Phalcon\Http\Message\Request;
use Phalcon\Http\Message\Uri;
$request = new Request();
$uri = new Uri('https://api.phalcon.io/companies/1');
$jwtToken = 'abc.def.ghi';
$request = $request
->withMethod('POST')
->withHeader('Authorization', 'Bearer ' . $jwtToken)
->withHeader('Content-Type', 'application/json')
;
$result = $httpClient->send($request);
Phalcon\Http\Message\Request
object and a new Phalcon\Http\Message\Uri
object with the target URL. Following that we define the method (POST) and additional headers that we need to send with our request. The client then sends the request by using the request object.<?php
use Phalcon\Http\Message\Request;
$jwtToken = 'abc.def.ghi';
$request = new Request(
'POST',
'https://api.phalcon.io/companies/1',
'php://memory',
[
'Authorization' => 'Bearer ' . $jwtToken,
'Content-Type' => 'application/json',
]
);
$result = $httpClient->send($request);
<?php
use Locale;
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
// Locale could be something like 'en_GB' or 'en'
echo $locale;
Phalcon\Translate
offers multilingual capabilities to applications. This component allows you to display content in different languages, based on the user’s choice of language, available by the application.HTTP_ACCEPT_LANGUAGE
contents or using the getBestLanguage()
method of the Phalcon\Http\Request object)
.<?php
use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;
use Phalcon\Translate\InterpolatorFactory;
use Phalcon\Translate\TranslateFactory;
/**
* @property Phalcon\Http\Request $request
* @property Phalcon\Mvc\View $view
*/
class UserController extends Controller
{
public function indexAction()
{
$this->view->name = 'Mike';
$this->view->t = $this->getTranslator();
}
/**
* @return NativeArray
*/
private function getTranslator(): NativeArray
{
// Ask browser what is the best language
$language = $this->request->getBestLanguage();
$messages = [];
$translationFile = 'app/messages/' . $language . '.php';
if (true !== file_exists($translationFile)) {
$translationFile = 'app/messages/en.php';
}
require $translationFile;
$interpolator = new InterpolatorFactory();
$factory = new TranslateFactory($interpolator);
return $factory->newInstance(
'array',
[
'content' => $messages,
]
);
}
}
getTranslator()
method is available in the controller for all actions that require it. You could of course introduce a caching mechanism to store the translation adapter in your cache (based on the language selected i.e. en.cache, de-cache etc.)Phalcon\Collection
is an object oriented array. It offers speed, as well as implementations of various PHP interfaces. These are :<?php
use Phalcon\Collection;
$data = [
'colors' => [
'red',
'white',
'blue',
],
'year' => 1776,
];
$collection = new Collection($data);