Low overhead
PHP C-extension (Phalcon)
-
Zephir/C extensions are loaded together with PHP one time on the web server's daemon start process
-
Classes and functions provided by the extension are ready to use for any application
-
The code is compiled and isn't interpreted because it's already compiled to a specific platform and processor
-
Thanks to its low-level architecture and optimizations Phalcon provides the lowest overhead for MVC-based applications
MVC
Build single and multi-module applications with ease and pleasure. Using the file structure, scheme and patterns you already know.
single/
app/
controllers/
models/
views/
public/
css/
img/
js/
multiple/
apps/
frontend/
controllers/
models/
views/
Module.php
backend/
controllers/
models/
views/
Module.php
public/
../
Dependency Injection
Phalcon is built upon a powerful yet easy to understand and use pattern called Dependency Injection. Initialize or define services once - and use them virtually anywhere throughout the application.
$di = new Phalcon\DI();
$di->set("request", new Phalcon\Http\Request());
..
$request = $di->getShared('request');
Restful Services
Writing REST servers and applications has never been easier. No boilerplate. Simple services will fit in one file.
use Phalcon\Mvc\Micro;
$app = new Micro();
$app->get(
'/check/status',
function () {
return $this
->response
->setJsonContent(
[
'status' => 'important',
]
)
;
}
);
$app->handle();
Autoloader
Register namespaces, prefixes, directories or classes. Take advantage of the autoloader events and maintain full control over what files are loaded and from where.
use Phalcon\Loader;
$loader = new Loader();
$loader->registerNamespaces(
[
'Example\Base' => 'vendor/example/base/',
'Example\Adapter' => 'vendor/example/adapter/',
'Example' => 'vendor/example/',
]
);
$loader->register();
Router
Routing as it supposed to be. Nothing more. Nothing less.
$router = new \Phalcon\Mvc\Router();
$router->add(
'/admin/users/my-profile',
[
'controller' => 'users',
'action' => 'profile',
]
);
-
ORM
对象关系映射
-
PHQL
强大且安全的Phalcon查询语言PHQL
-
事务
Phalcon中的事务可确保数据完整性安全。
-
缓存
利用Phalcon提供的许多后端缓存来提高性能
ORM
A powerful ORM is provided by Phalcon allowing you to manipulate database records as classes and objects. MySQL, PostgreSQL and SQLite are supported out of the box.
use Invoices;
use Phalcon\Mvc\Model;
class Customers extends Model
{
public $cst_id;
public $cst_name;
public function initialize()
{
$this->hasMany(
'cst_id',
Invoices::class,
'inv_cst_id'
);
}
}
PHQL
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. To achieve the highest performance possible, Phalcon provides a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
$phql = 'SELECT * '
. 'FROM Formula\Cars '
. 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);
$phql = 'SELECT Formula\Cars.name '
. 'FROM Formula\Cars '
. 'ORDER BY Formula\Cars.name';
$query = $manager->createQuery($phql);
$phql = 'SELECT c.name '
. 'FROM Formula\Cars c '
. 'ORDER BY c.name';
$query = $manager->createQuery($phql);
$phql = 'SELECT c.* '
. 'FROM Cars AS c '
. 'ORDER BY c.name';
$cars = $manager->executeQuery($phql);
foreach ($cars as $car) {
echo "Name: ", $car->name, "\n";
}
Transactions
When a process performs multiple database operations, it might be important that each step is completed successfully so that data integrity can be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data is committed to the database.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$manager = new Manager();
$transaction = $manager->get();
$invoices = Invoices::find(
'inv_cst_id = 123'
);
foreach ($invoices as $invoice) {
$invoice->setTransaction($transaction);
if ($invoice->delete() == false) {
foreach ($invoice->getMessages() as $message) {
$transaction
->rollback($message->getMessage());
}
}
}
$transaction->commit();
echo "Robots were deleted successfully!";
} catch (Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
Cache
The cache component allows faster access to frequently used or already processed data. It supports many backends such as Redis, Memcached, Mongo, Files, Apc and more
use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\Serializer\SerializerFactory;
$serializerFactory = new SerializerFactory();
$adapterFactory = new AdapterFactory($serializerFactory);
$options = [
'defaultSerializer' => 'Json',
'lifetime' => 7200
];
$adapter = $adapterFactory
->newInstance('apcu', $options);
$cache = new Cache($adapter);
Template Engines
Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
<html>
<body>
<div class='top'>
<?php $this->partial('shared/ad_banner'); ?>
</div>
<div class='content'>
<h1>Robots</h1>
<p>
Check out our specials for robots:
</p>
...
</div>
<div class='footer'>
<?php $this->partial('shared/footer'); ?>
</div>
</body>
</html>
Template Engine (Volt)
Volt is an ultra-fast and designer friendly templating language written in Zephir/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.
{
{% block last_products %}
{% for prod in products %}
* Name: {{ prod.name|e }}
{% if prod.status == 'Active' %}
Price: {{ prod.price + prod.taxes/100}}
{% endif %}
{% endfor %}
{% endblock %}
i18n
The component Phalcon\Translate aids in creating multilingual applications. Applications using this component, display content in different languages, based on the user's chosen language supported by the application.
$messages = [
'hi' => 'Hello',
'bye' => 'Good Bye',
'hi-name' => 'Hello %name%',
'song' => 'This song is %song%'
];
$messages = [
'hi' => 'Hola',
'bye' => 'Adiós',
'hi-name' => 'Hola %name%',
'song' => 'Esta canción es %song%'
];
use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;
class UserController extends Controller
{
protected function getTranslation()
{
$language = $this
->request
->getBestLanguage();
$fileName = 'app/messages/'
. $language
. '.php';
if (file_exists($fileName) {
require $fileName;
} else {
require 'app/messages/en.php';
}
return new NativeArray(
array(
'content' => $messages
)
);
}
public function indexAction()
{
$this->view->name = 'Mike';
$this->view->t = $this
->getTranslation();
}
}
<p><?php echo $t->_('hi'), ' ', $name; ?></p>
Forms Builder
Each element in the form can be rendered as required by the developer. Internally, Phalcon\Tag is used to produce the correct HTML for each element and you can pass additional HTML attributes as the second parameter of render():
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;
$form = new Form();
$form->add(new Text('name'));
$form->add(new Text('telephone'));
$form->add(
new Select(
'telephoneType',
array(
'H' => 'Home',
'C' => 'Cellphone'
)
)
);
Flash messages
Use the flash notifier to show notifications to a user in a web application:
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function saveAction()
{
$this->flash->error(
'there were errors in this form'
);
$this->flash->success(
'yes!, everything is fine'
);
$this->flash->notice(
'this is a notice for users'
);
$this->flash->warning(
'this is just a warning'
);
}
}
ACL
This is how you can built the access control list (ACL):
use Phalcon\Acl;
use Phalcon\Acl\Enum;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory;
$acl = new Memory();
$acl->setDefaultAction(Enum::DENY);
$roles = array(
'users' => new Role('Users'),
'guests' => new Role('Guests')
);
foreach ($roles as $role) {
$acl->addRole($role);
}
Sharding
Attach models to different databases
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Db\Adapter\Pdo\PostgreSQL;
$container->set(
'dbMysql',
function () {
return new Mysql(
[
'host' => 'localhost',
'username' => 'root',
'password' => 'secret',
'dbname' => 'tutorial',
]
);
}
);
$container->set(
'dbPostgres',
function () {
return new PostgreSQL(
[
'host' => 'localhost',
'username' => 'postgres',
'password' => '',
'dbname' => 'invo',
]
);
}
);
Encryption
Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the openssl PHP's encryption library.
use Phalcon\Crypt;
$crypt = new Crypt();
$key = 'This is a secret key (32 bytes).';
$text = 'The text you want to encrypt.';
$encrypted = $crypt->encrypt($text, $key);
echo $crypt->decrypt($encrypted, $key);
Events Management
An EventsManager allows us to attach listeners to a particular type of event. The type that interests us now is 'dispatch'. The following code filters all events produced by the Dispatcher:
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager;
$container->set(
'dispatcher',
function () {
$manager = new Manager();
$manager->attach(
'dispatch:beforeExecuteRoute',
new SecurityPlugin
);
$manager->attach(
'dispatch:beforeException',
new NotFoundPlugin
);
$dispatcher = new Dispatcher();
$dispatcher
->setEventsManager($manager);
return $dispatcher;
}
);