Documentation

內容目录

Welcome

欢迎来到 Phalcon 框架, 一种崭新的 PHP 框架。我们的使命是给开发者一个开发 web 站点和应用的高级工具,让开发者不用担心框架的性能问题.

Phalcon 是什么

Phalcon 是开源、全功能栈、使用 C 扩展编写、针对高性能优化的 PHP 5 框架。 开发者不需要学习和使用 C 语言的功能, 因为所有的功能都以 PHP 类的方式暴露出来,可以直接使用。 Phalcon 也是松耦合的,可以根据项目的需要任意使用其他对象。

Phalcon 不只是为了卓越的性能, 我们的目标是让它更加健壮,拥有更加丰富的功能以及更加简单易于使用!

目录

安装

安装(Installation)

作为PHP C拓展形式的Phalcon,需要一个略微不同于传统PHP的库或框架的安装方法。你可以选择一个当前系统的一个二进制包下载,或者使用源代码构建它。

Windows

要在Windows上使用Phalcon,你可以下载一个DLL库。编辑php.ini文件,并且在最后附加上:

extension=php_phalcon.dll

重启你的Web服务器。

下面的视频是一个在Windows上安装Phalcon的步骤指南:

Linux/Solaris
Debian / Ubuntu

添加仓库到你的分发:

# 稳定版本
curl -s https://packagecloud.io/install/repositories/phalcon/stable/script.deb.sh | sudo bash

# 试运行版
curl -s https://packagecloud.io/install/repositories/phalcon/nightly/script.deb.sh | sudo bash

这个仅仅需要做一次, 除非你的distribution发生了变化或者你想选择从稳定版切换到试运行版.

安装 Phalcon:

sudo apt-get install php5-phalcon

# 或者 PHP7 版本

sudo apt-get install php7.0-phalcon
RPM分发(RPM distributions) (比如 CentOS)

添加仓库到你的分发:

# 稳定版本
curl -s https://packagecloud.io/install/repositories/phalcon/stable/script.rpm.sh | sudo bash

# 试运行版
curl -s https://packagecloud.io/install/repositories/phalcon/nightly/script.rpm.sh | sudo bash

这个仅仅需要做一次, 除非你的distribution发生了变化或者你想选择从稳定版切换到试运行版.

安装 Phalcon:

sudo yum install php56u-phalcon

# 或者 PHP7 版本

sudo yum install php70u-phalcon
从源码编译(Compile from source)

在Linux/Solaris系统下,你能很轻易从源代码编译和安装这个拓展:

必要的包:

  • PHP >= 5.5 开发资源
  • GCC 编译器 (Linux/Solaris)
  • Git (如果不是已经安装在你的系统,且你没有从Github上下载这个包并通过FTP/SFTP上传到你的服务器上)

通用平台下安装指定的软件包:

# Ubuntu
sudo apt-get install php5-dev libpcre3-dev gcc make php5-mysql

# Suse
sudo yast -i gcc make autoconf php5-devel php5-pear php5-mysql

# CentOS/RedHat/Fedora
sudo yum install php-devel pcre-devel gcc make

# Solaris
pkg install gcc-45 php-56 apache-php56

创建扩展:

git clone git://github.com/phalcon/cphalcon.git

cd cphalcon/build

sudo ./install

添加扩展到你的php配置文件:

# Suse: 在 /etc/php5/conf.d/ 目录下添加一个名为 phalcon.ini 的文件, 内容如下:
extension=phalcon.so

# CentOS/RedHat/Fedora: 在 /etc/php.d/ 目录下添加一个名为 phalcon.ini 的文件, 内容如下:
extension=phalcon.so

# Ubuntu/Debian with apache2: 在 /etc/php5/apache2/conf.d/ 目录下添加一个名为 30-phalcon.ini 的文件, 内容如下:
extension=phalcon.so

# Ubuntu/Debian with php5-fpm: 在 /etc/php5/fpm/conf.d/ 目录下添加一个名为 30-phalcon.ini 的文件, 内容如下:
extension=phalcon.so

# Ubuntu/Debian with php5-cli: 在 /etc/php5/cli/conf.d/ 目录下添加一个名为 30-phalcon.ini 的文件, 内容如下:
extension=phalcon.so

重启Web服务器.

如果你在 Ubuntu/Debian 下使用 php5-fpm,重启命令为:

sudo service php5-fpm restart

Phalcon自动检测你的系统架构,然而,您可以强制编译为一个特定的架构:

cd cphalcon/build

# 下面的选择一个执行:
sudo ./install 32bits
sudo ./install 64bits
sudo ./install safe

如果自动安装失败,请尝试手动编译安装:

cd cphalcon/build/64bits

export CFLAGS="-O2 --fvisibility=hidden"

./configure --enable-phalcon

make && sudo make install
Mac OS X

在Mac OS X系统中你可以通过源代码来编译和安装扩展:

要求

提前要有的包:

  • PHP >= 5.5 开发资源
  • XCode
# brew
brew tap homebrew/homebrew-php
brew install php55-phalcon
brew install php56-phalcon

# MacPorts
sudo port install php55-phalcon
sudo port install php56-phalcon

添加扩展到你的PHP配置文件。

FreeBSD

对于FreeBSD,仅仅只需要简单的命令进行安装:

pkg_add -r phalcon

或者

export CFLAGS="-O2 --fvisibility=hidden"

cd /usr/ports/www/phalcon

make install clean
确认安装(Checking your installation)

请检查你的 phpinfo() 输出了一个”Phalcon”部分引用或者执行以下代码片段:

<?php print_r(get_loaded_extensions()); ?>

Phalcon 拓展应该作为输出的一部分出现:

Array
(
    [0] => Core
    [1] => libxml
    [2] => filter
    [3] => SPL
    [4] => standard
    [5] => phalcon
    [6] => pdo_mysql
)
安装说明(Installation Notes)

常见Web服务器的安装说明:

Apache 安装说明(Apache Installation Notes)

Apache 是一个流行且出名的web服务器,并且可以支持很多平台。

Apache 下配置 Phalcon(Configuring Apache for Phalcon)

以下内容是你可能在使用Apache下搭建Phalcon时可能会用到的配置。这些内容重点关注于mod_rewrite模块的配置,以便可以使用友好的链接和路由组件 router component 。通常一个应用会有以下目录结构:

test/
  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/
    index.php
在主文档根目录下(Directory under the main Document Root)

这是一种最为常用的情况,应用安装在根目录下的任意一个目录。对于这种情况,我们使用两个.htaccess文件,第一个用于隐藏应用转发全部请求到对应文档根目录(public/)的相关代码。

# test/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule  ^$ public/    [L]
    RewriteRule  ((?s).*) public/$1 [L]
</IfModule>

然后第二个.htaccess位于public/下,并将全部的URI重定向到public/index.php文件。

# test/public/.htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

如果你不想使用这些.htaccess文件,你可以将这些配置移到apache的主配置文件中:

<IfModule mod_rewrite.c>

    <Directory "/var/www/test">
        RewriteEngine on
        RewriteRule  ^$ public/    [L]
        RewriteRule  ((?s).*) public/$1 [L]
    </Directory>

    <Directory "/var/www/test/public">
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
    </Directory>

</IfModule>
虚拟主机(Virtual Hosts)

第二份配置则允许你可以将一个Phalcon应用安装在虚拟主机:

<VirtualHost *:80>

    ServerAdmin admin@example.host
    DocumentRoot "/var/vhosts/test/public"
    DirectoryIndex index.php
    ServerName example.host
    ServerAlias www.example.host

    <Directory "/var/vhosts/test/public">
        Options All
        AllowOverride All
        Allow from all
    </Directory>

</VirtualHost>

如果你使用的Apache版本为2.4或者以上:

<VirtualHost *:80>

    ServerAdmin admin@example.host
    DocumentRoot "/var/vhosts/test/public"
    DirectoryIndex index.php
    ServerName example.host
    ServerAlias www.example.host

    <Directory "/var/vhosts/test/public">
        Options All
        AllowOverride All
        Require all granted
    </Directory>

</VirtualHost>
Nginx 安装说明(Nginx Installation Notes)

Nginx 是一个免费的,开源的高性能的HTTP服务器和反向代理服务器,同样也可作为IMAP/POP3代理服务器。不同于传统的服务器,Nginx 不依赖线程去处理请求。相反,它使用一个高扩展的事件驱动(异步)架构。 这种架构对系统资源的消耗很低,但更重要的是,承载了非常高的负载,并发能力很强。

PHP-FPM (FastCGI 进程管理器)通常用来允许 Nginx 来处理PHP文件。到了如今,PHP-FPM 已经捆绑在所有的PHP发行版中。Phalcon + Nginx + PHP-FPM 提供了一套强大的工具集,为你的PHP应用提供最强大性能。

Niginx 下配置 Phalcon(Configuring Nginx for Phalcon)

下面是nginx可以合Phalcon配合使用的大概配置:

基础配置(Basic configuration)

使用 $_GET[‘_url’] 作为 URLs的源:

server {
    listen      80;
    server_name localhost.dev;
    root        /var/www/phalcon/public;
    index       index.php index.html index.htm;
    charset     utf-8;

    location / {
        try_files $uri $uri/ /index.php?_url=$uri&$args;
    }

    location ~ \.php {
        fastcgi_pass  unix:/run/php-fpm/php-fpm.sock;
        fastcgi_index /index.php;

        include fastcgi_params;
        fastcgi_split_path_info       ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }
}

使用 $_SERVER[‘REQUEST_URI’] 作为 URLs的源:

server {
    listen      80;
    server_name localhost.dev;
    root        /var/www/phalcon/public;
    index       index.php index.html index.htm;
    charset     utf-8;

    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        try_files     $uri =404;

        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index /index.php;

        include fastcgi_params;
        fastcgi_split_path_info       ^(.+\.php)(/.+)$;
        fastcgi_param PATH_INFO       $fastcgi_path_info;
        fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }
}
Cherokee 安装说明(Cherokee Installation Notes)

Cherokee 是一个高性能的web服务器。它非常快,运行稳定并且易于配置。

针对Phalcon的Cherokee配置

Cherokee提供了友好的界面来设置几乎web服务器全部可用的配置。 使用root帐号执行 /path-to-cherokee/sbin/cherokee-admin 可以开启cherokee管理员。

_images/cherokee-1.jpg

通过点击“vServers”便可创建一个新的虚拟机,然后添加一个新的虚拟服务器:

_images/cherokee-2.jpg

屏幕左栏会显示最近添加的虚拟服务器。在“Behaviors”(行为)标签中,你可以看到这个虚拟服务器一系列默认的行为操作。 点击“Rule Management”(规则管理)按钮。删除“Directory /cherokee_themes”和“Directory /icons”这些标签。

_images/cherokee-3.jpg

接着使用向导添加“PHP Language”(PHP语言)。这样你就可以运行你的PHP应用了:

_images/cherokee-4.jpg

通常这个操作不需要额外的配置。在“Manual Configuration”(配置管理)部分,添加另一个操作。 在“Rule Type”(规则类型)下拉中选择“File Exists”(已存在的文件),然后确保选项“Match any file”(匹配任何文件)勾选了enabled(开启):

_images/cherokee-55.jpg

在“Handler”(处理器)标签中选择“List & Send”作为处理器:

_images/cherokee-7.jpg

编辑“Default”(默认)行为以便可以开启URL重写引擎。修改处理器为“Redirection”(重定向), 然后将以下正则表达式 ^(.*)$ 添加到引擎中:

_images/cherokee-6.jpg

最后,确保上面的行为操作符合以下的顺序:

_images/cherokee-8.jpg

在浏览器中执行对应的应用:

_images/cherokee-9.jpg
使用 PHP 内置 web 服务器(Using PHP Built-in webserver)

对于PHP 5.4.0或以上版本, 你可以为项目开发使用PHP内置的web服务器。

为了启动web服务器,需要:

php -S localhost:8000 -t /public

如果你想重写URI并指向index.php文件,可以使用以下路由文件(.htrouter.php):

<?php
if (!file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) {
    $_GET['_url'] = explode('?',$_SERVER['REQUEST_URI'])[0];
}
return false;

然后这样启动服务器:

php -S localhost:8000 -t /public .htrouter.php

最然打开浏览器输入并跳转到 http://localhost:8000/,检测是否可以正常访问。

Phalcon 开发工具(Phalcon Developer Tools)

Phalcon提供的这个开发工具主要是用来辅助开发,比如生成一些程序的基本框架,生成控制器模型等。使用这个工具我们只需要一个简单的命令即可生成应用的基本框架。

如果你喜欢使用web版而非console版本的程序,那么在这里 blog post 可以看到更多的内容。
下载(Download)

我们可以从 Github 上下载或克隆下来这个跨平台的开发辅助工具。

安装(Installation)

下面详尽的说明了如何在不同的操作系统平台上安装这个辅助开发工具:

Windows 系统下使用 Phalcon 开发工具(Phalcon Developer Tools on Windows)

下面这些步骤将指导您在 windows 上完成安装 Phalcon 开发者工具。

预备知识(Prerequisites)

运行 Phalcon 工具必须先安装 PHP Phalcon 扩展包。如果您还没有安装,请参考安装指南 Installation

下载(Download)

你可以从 Download 部分下载一个包含开发工具的跨平台软件包,你也可以从 Github 克隆。

在Windows平台下,你需要把 Phalcon 工具作为 PHP 可执行文件配置到系统路径。如果你下载了 Phalcon 工具的zip压缩文件,提取它到本地的任何路径,例如:c:\phalcon-tools。你需要按照下面步骤继续操作。选择”phalcon.bat” 文件,鼠标右键”编辑”:

_images/path-0.png

把路径设为你安装 Phalcon 工具的路径(设置 PTOOLSPATH=C:phalcon-tools):

_images/path-01.png

保存修改。

添加 PHP 以及工具所在路径到系统环境变量 PATH (Adding PHP and Tools to your system PATH)

因为脚本是用PHP编写的,你需要在自己的机器上安装PHP。由于你安装了PHP,可执行文件可以位于不同的地方。搜索php.exe文件,复制它的路径。例如,如果你使用最新的 WAMP, PHP 的路径为: C:\wampbin\php\php5.3.10\php.exe

找到桌面的”计算机”图标,右键选择”属性”:

_images/path-1.png

选择”高级系统设置”,然后点击”环境变量”的按钮。

_images/path-2.png

找到”path”

_images/path-3.png

这一步要非常小心!你需要在很长的路径字符串找到 php.exe,在它后面添加 Phalcon 工具的路径。使用”;”来分隔不同的路径。

_images/path-4.png

点击”确定”,然后关闭对话框。按”Windows Key” + “R”,键

_images/path-5.png

输入”cmd”,按回车键打开 windows 命令行程序:

_images/path-6.png

输入”php -v” 和 “phalcon”,然后你将看到类似下面的效果:

_images/path-7.png

祝贺你现在完成了Phalcon 工具的安装。

Mac OS X 系统下使用 Phalcon 开发工具(Phalcon Developer Tools on Mac OS X)

These steps will guide you through the process of installing Phalcon Developer Tools for OS/X.

预备知识(Prerequisites)

The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions.

下载(Download)

You can download a cross platform package containing the developer tools from the Download section. You can also clone it from Github.

Open the terminal application:

_images/mac-1.png

Copy & Paste the commands below in your terminal:

git clone git://github.com/phalcon/phalcon-devtools.git

Then enter the folder where the tools were cloned and execute ”. ./phalcon.sh”, (don’t forget the dot at beginning of the command):

cd phalcon-devtools/

. ./phalcon.sh

In the terminal window, type the following commands to create a symbolic link to the phalcon.php script:

ln -s ~/phalcon-tools/phalcon.php ~/phalcon-tools/phalcon

chmod +x ~/phalcon-tools/phalcon

Type the command “phalcon” and you will see something like this:

_images/mac-5.png

Congratulations you now have Phalcon tools installed!

Linux 系统下使用 Phalcon 开发工具(Phalcon Developer Tools on Linux)

These steps will guide you through the process of installing Phalcon Developer Tools for Linux.

预备知识(Prerequisites)

The Phalcon PHP extension is required to run Phalcon Tools. If you haven’t installed it yet, please see the Installation section for instructions.

下载(Download)

You can download a cross platform package containing the developer tools from the Download section. Also you can clone it from Github.

Open a terminal and type the command below:

git clone git://github.com/phalcon/phalcon-devtools.git
_images/linux-1.png

Then enter the folder where the tools were cloned and execute ”. ./phalcon.sh”, (don’t forget the dot at beginning of the command):

cd phalcon-devtools/

. ./phalcon.sh
_images/linux-2.png

Create a symbolink link to the phalcon.php script:

ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon

chmod ugo+x /usr/bin/phalcon

Congratulations you now have Phalcon tools installed!

获取可用的命令(Getting Available Commands)

我们可以在虚拟控制台上输入如下命令: phalcon commands

$ phalcon commands

Phalcon DevTools (3.0.0)

Available commands:可用命令
  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)
生成项目框架(Generating a Project Skeleton)

我们可以使用Phalcon开发辅助工具生成预先定义的项目架构。 默认情况下,phalcon开发辅助工具会使用apache的mod_rewrite来生成程序的骨架. 要创建项目我们只需要在我们的 web服务器根目录下输入如下命令:

$ pwd

/Applications/MAMP/htdocs

$ phalcon create-project store

执行命令后会生成如下的文档结构的项目:

_images/tools-2.png

我们可以在命令上加 –help 以显示帮助信息(下面的帮助中的中文是翻译时加上去的):

$ phalcon project --help

Phalcon DevTools (3.0.0)

Help:帮助
  Creates a project 创建项目

Usage:用法
  project [name] [type] [directory] [enable-webtools]

Arguments: 参数
  help    Shows this help text 显示此帮助信息

Example 例子
  phalcon project store simple

Options: 选项
 --name               Name of the new project 新项目的名字
 --enable-webtools    Determines if webtools should be enabled [optional] 此选项决定了新的项目中是否使用webtools开发辅助组件
 --directory=s        Base path on which project will be created [optional] 在何外创建项目
 --type=s             Type of the application to be generated (cli, micro, simple, modules) 应用的种类(微型,简单,多模块,console等)
 --template-path=s    Specify a template path [optional] 指定模板路径
 --use-config-ini     Use a ini file as configuration file [optional] 使用ini文件作为配置保存文件
 --trace              Shows the trace of the framework in case of exception. [optional] 出错时是否显示框架的trace信息
 --help               Shows this help 显示帮助

我们访问新生成项目的地址显示如下:

_images/tools-6.png
生成控制器(Generating Controllers)

我们可以使用phalcon create-controller –name test或phalcon controller –name test来生成名为test的控制器. 当然要使用此命令当前的执行命令目录必须为已存在的phalcon项目内.

$ phalcon create-controller --name test

上面的命令会生成如下代码:

<?php

use Phalcon\Mvc\Controller;

class TestController extends Controller
{
    public function indexAction()
    {

    }
}
数据库配置(Preparing Database Settings)

当我们使用phalcon的辅助开发工具生成项目时,则生成的配置信息会被放在 app/config/config.ini 文件内。 我们必须要正确的配置连接信息才可生成模型或基本的CRUD操作。

可以在config.ini中进行修改配置信息:

[database]
adapter  = Mysql
host     = "127.0.0.1"
username = "root"
password = "secret"
dbname   = "store_db"

[phalcon]
controllersDir = "../app/controllers/"
modelsDir      = "../app/models/"
viewsDir       = "../app/views/"
baseUri        = "/store/"
生成模型(Generating Models)

使用phalcon开发辅助工具我们可以有若干种方式来生成模型。 我人可以有选择的生成若干个模型或是全部生成。 亦可以指定生成公有属性或是生成setter和getter方法。

Options:
--name=s Table name 表名
--schema=s Name of the schema. [optional] schema名
--namespace=s Model’s namespace [optional] 模型命名空间
--get-set Attributes will be protected and have setters/getters. [optional] 设置字段访问属性为私有 并添加setters/getters方法
--extends=s Model extends the class name supplied [optional] 指定扩展类名
--excludefields=l
 Excludes fields defined in a comma separated list [optional]
--doc Helps to improve code completion on IDEs [optional] 辅助IDE的自动完成功能
--directory=s Base path on which project will be created [optional] 项目的根目录
--force Rewrite the model. [optional] 重写模型
--trace Shows the trace of the framework in case of exception. [optional] 出错时显示框架trace信息
--mapcolumn Get some code for map columns. [optional] 生成字映射的代码
--abstract Abstract Model [optional] 抽象模型

最简单的生成模型的方式:

$ phalcon model products
$ phalcon model --name tablename

所有的字段设置为公有:

<?php

use Phalcon\Mvc\Model;

class Products extends Model
{
    /**
     * @var integer
     */
    public $id;

    /**
     * @var integer
     */
    public $typesId;

    /**
     * @var string
     */
    public $name;

    /**
     * @var string
     */
    public $price;

    /**
     * @var integer
     */
    public $quantity;

    /**
     * @var string
     */
    public $status;
}

我们可以在生成模型时指定 –get-set 参数以实现对字面的保护, 这样我们可以在setter/getter方法里执行一些业务逻辑。

<?php

use Phalcon\Mvc\Model;

class Products extends Model
{
    /**
     * @var integer
     */
    protected $id;

    /**
     * @var integer
     */
    protected $typesId;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $price;

    /**
     * @var integer
     */
    protected $quantity;

    /**
     * @var string
     */
    protected $status;


    /**
     * 设置字段 id 值的方法
     *
     * @param integer $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * 设置字段 typsId 值的方法
     *
     * @param integer $typesId
     */
    public function setTypesId($typesId)
    {
        $this->typesId = $typesId;
    }

    // ...

    /**
     * 返回字段 status 值
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }
}

另一个非常好的特性即是在我们多次生成模型时,原有的对模型的更改依然会存在。 这样我们就可以不用担心对模型的属性进行修会被后来再次执模型的生成命令所覆盖。下面的截图显示了这是如何工作的:

生成基本的 CRUD(Scaffold a CRUD)

使用phalcon开发辅助工具我们可以直接快速的生成一个模型的CRUD操作。 如果我们想快速的生成模型的CRUD操作只需要使用phalcon辅助开发工具的中scaffold命令即可。

代码生成后,你可以根据自己的需要修改生成的代码。很多开发者可能不会去使用这个功能,其实这东西有时不是太好用,很多时候开发者往往会手动的书写相关代码。使用scaffold产生的代码可以 帮助我们理解框架是如何工作的当然也可以帮助我们制作出快速原型来。 下面的截图展示了基于products表的scaffold:

$ phalcon scaffold --table-name products

scaffold生成器会在相关的文件夹中生成若干个文档。 下面是所生成文件的概览:

在生成的Products控制器中,我们可以看到一个搜索表单和一个生成新product的链接:

_images/tools-10.png

在创建页面我们可以生成经过验证的Products记录。 Phalcon会自动的验证数据库中的非空字段。

_images/tools-11.png

执行搜索后,分页组件会显示颁后的结果。 我们在结果列表的前面放置Edit或Delete链接,以实现相应的操作。

_images/tools-12.png
工具的 Web 界面(Web Interface to Tools)

另外,如果你喜欢我们还可以在生成项目时通过添加参数以实现在项目中使用Phalcon开发工具的web接口。 下面的视频中展示了如何工作的:

集成工具到 PhpStorm(Integrating Tools with PhpStorm IDE)

下面的视频中展示了如何在 PhpStorm IDE 中集成辅助开发工具。 这个配置步骤也适用于其它的PHP IDE.

结束语(Conclusion)

Phalcon开发辅助工具为我们提供了一种简易的产生应用代码的方法, 这可以减少开发时间及潜在的错误。

教程

教程 1:让我们通过例子来学习(Tutorial 1: Let’s learn by example)

通过这第一个教程,我们将引导您从基础完成创建简单的带有注册表单的应用。 我们也将解释框架行为的基本方面。如果您对Phalcon的自动代码生成工具有兴趣, 您可以查看 developer tools

使用本指南的最好方法就是依次按照每一步来做。你可以得到完整的代码 点击这里.

文件结构(File structure)

Phalcon不会强制要求应用程序的开发遵循特定的文件结构。因为它是松散耦合的,你可以实现Phalcon驱动的应用程序,以及使用对你来说最舒服的文件结构。

本教程的目的以此为起点,我们建议使用以下结构:

tutorial/
  app/
    controllers/
    models/
    views/
  public/
    css/
    img/
    js/

需要注意的是,你不需要任何有关Phalcon的 “library” 目录。该框架已经被加载到内存中,供您使用。

在此之前, 请确认你已经成功的 installed Phalcon, 并设置了:doc:Nginx <nginx>, Apache 或者 Cherokee.

引导程序(Bootstrap)

你需要创建的第一个文件是引导文件。这个文件很重要; 因为它作为你的应用程序的基础,用它来控制应用程序的各个方面。 在这个文件中,你可以实现组件的初始化和应用程序的行为。

基本上, 它负责做三件事情:

  1. 设置自动加载器.
  2. 配置依赖注入.
  3. 处理应用请求.
自动加载(Autoloaders)

我们可以看出,引导程序的第一部分是注册一个自动加载器。在这个应用程序里,它将用于加载控制器和模型类。例如,我们可以为控制器注册一个或多个目录来增加应用程序的灵活性的。在我们的例子中,我们使用了 Phalcon\Loader 组件。

有了它,我们可以加载使用各种策略类,但在这个例子中,我们选择了在预定义的目录中查找类:

<?php

use Phalcon\Loader;

// ...

$loader = new Loader();

$loader->registerDirs(
    [
        "../app/controllers/",
        "../app/models/",
    ]
);

$loader->register();
依赖管理(Dependency Management)

在使用Phalcon时必须理解的一个非常重要的概念是 依赖注入容器(dependency injection container). 这听起来复杂,但实际上非常简单实用。

服务容器是一个全局存储的将要被使用的应用程序功能包。每次框架需要的一个组件时,会请求这个使用协定好名称的服务容器。因为Phalcon是一个高度解耦的框架, Phalcon\Di 作为黏合剂,促使不同组件的集成,以一个透明的方式实现他们一起进行工作。

<?php

use Phalcon\Di\FactoryDefault;

// ...

// 创建一个 DI
$di = new FactoryDefault();

Phalcon\Di\FactoryDefaultPhalcon\Di 的一个变体。为了让事情变得更容易,它已注册了Phalcon的大多数组件。 因此,我们不需要一个一个注册这些组件。在以后更换工厂服务的时候也不会有什么问题。

在接下来的部分,我们注册了“视图(view)”服务,指示框架将去指定的目录寻找视图文件。由于视图并非PHP类,它们不能被自动加载器加载。

服务可以通过多种方式进行登记,但在我们的教程中,我们将使用一个匿名函数 anonymous function:

<?php

use Phalcon\Mvc\View;

// ...

// 设置视图组件
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../app/views/");

        return $view;
    }
);

接下来,我们注册一个基础URI,这样通过Phalcon生成包括我们之前设置的“tutorial”文件夹在内的所有的URI。 我们使用类 Phalcon\Tag 生成超链接,这将在本教程后续部分很重要。

<?php

use Phalcon\Mvc\Url as UrlProvider;

// ...

// 设置一个基础URI, 这样所有生成的URI都包含"tutorial"文件夹
$di->set(
    "url",
    function () {
        $url = new UrlProvider();

        $url->setBaseUri("/tutorial/");

        return $url;
    }
);
处理应用请求(Handling the application request)

在这个文件的最后部分,我们发现 Phalcon\Mvc\Application。其目的是初始化请求环境,并接收路由到来的请求,接着分发任何发现的动作;收集所有的响应,并在过程完成后返回它们。

<?php

use Phalcon\Mvc\Application;

// ...

$application = new Application($di);

$response = $application->handle();

$response->send();
把每个组件组合在一起(Putting everything together)

这个引导文件 tutorial/public/index.php 文件应该看起来像:

<?php

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;



// 注册一个自动加载器
$loader = new Loader();

$loader->registerDirs(
    [
        "../app/controllers/",
        "../app/models/",
    ]
);

$loader->register();



// 创建一个 DI
$di = new FactoryDefault();

// 设置视图组件
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../app/views/");

        return $view;
    }
);

// 设置一个基础URI, 这样所有生成的URI都包含"tutorial"文件夹
$di->set(
    "url",
    function () {
        $url = new UrlProvider();

        $url->setBaseUri("/tutorial/");

        return $url;
    }
);



$application = new Application($di);

try {
    // 处理请求
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo "Exception: ", $e->getMessage();
}

正如你所看到的,引导文件很短,我们并不需要引入任何其他文件。在不到30行的代码里,我们已经为自己设定一个灵活的MVC应用程序。

创建控制器(Creating a Controller)

默认情况下Phalcon会寻找一个名为“Index”的控制器。当请求中没有控制器或动作时,则使用“Index”控制器作为起点。这个“Index”控制器 (app/controllers/IndexController.php) 看起来类似:

<?php

use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    public function indexAction()
    {
        echo "<h1>Hello!</h1>";
    }
}

该控制器类必须有“Controller”后缀,且控制器动作必须有“Action”后缀。如果你从浏览器访问应用程序,你应该看到这样的事情:

_images/tutorial-1.png

恭喜, 让Phalcon带你飞!

输出到视图(Sending output to a view)

从控制器发送输出到屏幕上有时是必要的,但是在MVC社区,大多数纯粹主义者证明这样做不可取。一切必须传递给视图,视图负责在屏幕上输出数据。Phalcon将在最后执行的控制器的同名目录中,查找最后执行的动作的同名的视图。在我们的例子 (app/views/index/index.phtml) :

<?php echo "<h1>Hello!</h1>";

我们的控制器 (app/controllers/IndexController.php) 现在定义了一个空的动作:

<?php

use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    public function indexAction()
    {

    }
}

浏览器输出应该保持不变。当这个动作已经执行结束 Phalcon\Mvc\View 静态组件会自动创建。 学习更多关于 视图使用教程

设计注册表单(Designing a sign up form)

现在我们将改变index.phtml视图文件,添加一个链接到一个名为“signup”的新控制器。我们的目标是在应用程序中允许用户注册。

<?php

echo "<h1>Hello!</h1>";

echo PHP_EOL;

echo PHP_EOL;

echo $this->tag->linkTo(
    "signup",
    "Sign Up Here!"
);

生成的HTML代码显示一个锚 (“a”) HTML标签链接到一个新的控制器:

<h1>Hello!</h1>

<a href="/tutorial/signup">Sign Up Here!</a>

我们使用类 Phalcon\Tag 去生成标记。 这是一个让我们构建HTML标记的实用类。 关于生成HTML更详细的文章可以查看 视图助手

_images/tutorial-2.png

这是一个注册控制器 (app/controllers/SignupController.php):

<?php

use Phalcon\Mvc\Controller;

class SignupController extends Controller
{
    public function indexAction()
    {

    }
}

这个空index动作整洁的传递了表单定义给一个视图 (app/views/signup/index.phtml):

<h2>
    Sign up using this form
</h2>

<?php echo $this->tag->form("signup/register"); ?>

    <p>
        <label for="name">
            Name
        </label>

        <?php echo $this->tag->textField("name"); ?>
    </p>

    <p>
        <label for="email">
            E-Mail
        </label>

        <?php echo $this->tag->textField("email"); ?>
    </p>



    <p>
        <?php echo $this->tag->submitButton("Register"); ?>
    </p>

</form>

在浏览器中查看表单将显示类似的页面:

_images/tutorial-3.png

Phalcon\Tag 还提供了有用的方法来构建表单元素。

Phalcon\Tag::form() 方法只接受一个参数实例, 一个相对uri到这个应用的一个控制器/动作。

通过单击“Send”按钮,您将注意到框架抛出了一个异常,这表明我们是错过了在控制器中注册“register”动作。我们的 public/index.php 文件抛出这个异常:

Exception: Action “register” was not found on handler “signup”

实现该方法将移除异常:

<?php

use Phalcon\Mvc\Controller;

class SignupController extends Controller
{
    public function indexAction()
    {

    }

    public function registerAction()
    {

    }
}

如果你再点击“Send”按钮,您将看到一个空白页。提供的名称和电子邮件的输入的这个用户应该被存储在数据库中。根据MVC的指导方针,必须通过数据库交互模型,确保整洁的面向对象的代码。

创建模型(Creating a Model)

Phalcon带来的第一个完全用C语言编写的PHP ORM。它简化了开发, 而不是增加了开发的复杂性。

创建我们的第一个模型之前,我们需要在Phalcon以外创建一个数据库表。一个用来存储注册用户的简单表,可以这样定义:

CREATE TABLE `users` (
    `id`    int(10)     unsigned NOT NULL AUTO_INCREMENT,
    `name`  varchar(70)          NOT NULL,
    `email` varchar(70)          NOT NULL,

    PRIMARY KEY (`id`)
);

模型应该位于 app/models 目录 (app/models/Users.php). 这个模型对应“users”表:

<?php

use Phalcon\Mvc\Model;

class Users extends Model
{
    public $id;

    public $name;

    public $email;
}
设置数据库连接(Setting a Database Connection)

为了能够使用一个数据库连接,然后通过我们的模型访问数据,我们需要在我们的引导过程指定它。数据库连接是我们的应用程序可以使用的数个组件中的另一个服务:

<?php

use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

// 设置数据库服务
$di->set(
    "db",
    function () {
        return new DbAdapter(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "test_db",
            ]
        );
    }
);

使用正确的数据库参数,我们的模型已经准备和应用程序的其余部分工作。

使用模型保存数据(Storing data using models)

下一个步骤是从表单接收数据存储在表中。

<?php

use Phalcon\Mvc\Controller;

class SignupController extends Controller
{
    public function indexAction()
    {

    }

    public function registerAction()
    {
        $user = new Users();

        // 存储和检验错误
        $success = $user->save(
            $this->request->getPost(),
            [
                "name",
                "email",
            ]
        );

        if ($success) {
            echo "Thanks for registering!";
        } else {
            echo "Sorry, the following problems were generated: ";

            $messages = $user->getMessages();

            foreach ($messages as $message) {
                echo $message->getMessage(), "<br/>";
            }
        }

        $this->view->disable();
    }
}

然后我们实例化用户类,它对应于一个用户记录。类的公共属性映射到用户表中的记录的字段。在新记录中设置相应的值并调用:code:`save()`将在数据库中存储的数据记录。:code:`save()`方法返回一个布尔值,表示存储的数据是否成功。

ORM自动转义输入以防止SQL注入,所以我们只需要将请求传递给:code:`save()`方法。

附加的自动验证会验证字段定义为not null(必需)。如果我们不输入任何必需的注册表单中的字段,我们的屏幕将会看起来像这样:

_images/tutorial-4.png
结束语(Conclusion)

这是一个非常简单的教程,正如你所看到的,使用Phalcon很容易开始构建应用程序。Phalcon是一个在你的web服务器上没有干扰、易于开发、特性优良的扩展。我们邀请你继续阅读手册,这样你就可以发现Phalcon提供的附加功能!

教程 2:INVO简介(Tutorial 2: Introducing INVO)

在第二部分,我们将会说明一个完整的应用用来加深Phalcon的开发。 INVO是我们创建的一个程序样本。INVO是一个简单的用来允许用户生成发票的网站,并且可以做其他的任务,比如管理他们的客户或者产品。你可以从 Github 中复制它的代码。

同样,INVO使用 Bootstrap 做的前端框架。虽然这个应用不能生成发票,但是它仍然可以作为一个例子来理解框架是如何工作的。

项目结构(Project Structure)

一旦你从你的文档根目录复制了这个项目,你将会看到以下结构:

invo/
    app/
        config/
        controllers/
        forms/
        library/
        logs/
        models/
        plugins/
        views/
    cache/
        volt/
    docs/
    public/
        css/
        fonts/
        js/
    schemas/

正如你所知道的,Phalcon不会强求应用程序使用特定的文件结构。 这个项目提供了一个简单的MVC模型和公共文档根目录。

一旦你打开浏览器输入 http://localhost/invo 浏览应用程序你将会看到下面这样:

_images/invo-1.png

这个应用分为两部分,一部分是前端,这个是一个公开的部分,浏览者可以接收关于INVO的信息,也可以请求联系人信息。第二部分是后端,一个管理员区域,一个注册用户可以管理他/她的产品和客户。

路由(Routing)

INVO使用内置的标准路由. Router 组件. 路由符合以下格式:/:controller/:action/:params. 这就意味着第一部分URI是控制器,第二部分是方法,剩余的是参数。

下面的路由 /session/register 执行的是 SessionController 控制器和它的 registerAction方法。

配置(Configuration)

INVO有一个设置应用常规参数的配置文件。这个文件位于 app/config/config.ini,并且他在应用引导文件的最开始就开始加载 (public/index.php):

<?php

use Phalcon\Config\Adapter\Ini as ConfigIni;

// ...

// 读取配置
$config = new ConfigIni(
    APP_PATH . "app/config/config.ini"
);

Phalcon\Config 允许我们使用面向对象的方式来操作文件。在这个例子中,我们使用ini文件作为配置文件,然而,它对于配置文件有更多的适配支持。这个配置文件包含以下配置:

[database]
host     = localhost
username = root
password = secret
name     = invo

[application]
controllersDir = app/controllers/
modelsDir      = app/models/
viewsDir       = app/views/
pluginsDir     = app/plugins/
formsDir       = app/forms/
libraryDir     = app/library/
baseUri        = /invo/

Phalcon没有任何提前预约好的惯例配置。节帮助我们组织相应选项. 在这个文件里面有两个部分被用于后面的”application” 和 “database”.

自动加载(Autoloaders)

在启动文件(public/index.php)的第二部分是自动加载器:

<?php

/**
 * 自动加载配置
 */
require APP_PATH . "app/config/loader.php";

The autoloader registers a set of directories in which the application will look for the classes that it eventually will need.

<?php

$loader = new Phalcon\Loader();

// We're a registering a set of directories taken from the configuration file
$loader->registerDirs(
    [
        APP_PATH . $config->application->controllersDir,
        APP_PATH . $config->application->pluginsDir,
        APP_PATH . $config->application->libraryDir,
        APP_PATH . $config->application->modelsDir,
        APP_PATH . $config->application->formsDir,
    ]
);

$loader->register();

注意, 以上代码注册的目录是在配置文件中定义的. 唯一没有注册的目录是viewsDir, 因为它包含 HTML + PHP 文件但不是类. 同时, 也要注意我们使用了常量 APP_PATH, 这个常量在引导文件(public/index.php)中被定义, 允许我们对我们项目的根路径有一个参考:

<?php

// ...

define(
    "APP_PATH",
    realpath("..") . "/"
);
注册服务(Registering services)

在引导文件中加载的另外一个文件是 (app/config/services.php). 这个文件允许我们组织 INVO 不需要的文件.

<?php

/**
 * 加载应用服务
 */
require APP_PATH . "app/config/services.php";

服务注册已经在前面的教程中实现了, 利用一个闭包来实现惰性加载组件:

<?php

use Phalcon\Mvc\Url as UrlProvider;

// ...

/**
 * URL组件被用来生成应用中的各种URL
 */
$di->set(
    "url",
    function () use ($config) {
        $url = new UrlProvider();

        $url->setBaseUri(
            $config->application->baseUri
        );

        return $url;
    }
);

稍后我们将会深入讨论这个文件.

处理请求(Handling the Request)

如果我们忽略文件(public/index.php)的结束, 请求最终会被 Phalcon\Mvc\Application 处理, 初始化并运行所有必须的代码来让程序执行:

<?php

use Phalcon\Mvc\Application;

// ...

$application = new Application($di);

$response = $application->handle();

$response->send();
依赖注入(Dependency Injection)

看上面代码的第一行, Application 类的构造方法接受一个 $di 变量作为一个参数. 这个变量的用意是什么呢? Phalcon 是一个高度解耦的框架, 所以我们一个组件来充当胶水来让每个组件都能正常工作. 这个组件就是 Phalcon\Di. 这是一个服务容器, 可以执行依赖注入和服务定位, 实例化应用所需要的所有组件.

在容器中有多种注册服务的方法. 在INVO里, 大部分服务使用匿名函数或者闭包来进行注册的. 多亏了这个, 对象以惰性的方式被实例化, 减少了应用程序所需要的资源.

例如, 下面摘录了 Session 服务的注册. 当应用程序需要访问Session数据的时候, 匿名函数才会被调用:

<?php

use Phalcon\Session\Adapter\Files as Session;

// ...

// 在一个组件请求Session服务的时候, 启动Sesssion
$di->set(
    "session",
    function () {
        $session = new Session();

        $session->start();

        return $session;
    }
);

这里, 我们可以自动的更改适配器, 执行额外的初始化或者更多. 注意, 这个服务器是使用 “session” 名字进行注册的. 这是一个惯例, 来允许框架在服务容器中识别正在活动的服务.

一个请求可以使用多个服务和单独注册每个服务可以说是一个繁重的任务. 因此, 框架提供了 Phalcon\Di 的一个变种, 称作 Phalcon\Di\FactoryDefault 其任务是注册所有的服务来提供一个全栈框架.

<?php

use Phalcon\Di\FactoryDefault;

// ...

// FactoryDefault 依赖注入自动注册了正确的服务来提供了一个全栈框架
$di = new FactoryDefault();

它通过框架注册大部分组件服务作为标准提供. 如果我们需要重写某些已经定义的服务, 我们仅仅需要重新定义它, 就像上面的 “session” 和 “url”一样. 这就是变量 $di 存在的原因.

在下一章, 我们将会看到如何在INVO中实施认证和授权.

教程 3: 保护INVO(Tutorial 3: Securing INVO)

在这一章, 我们将继续解释INVO是如何构成的, 我们将讨论认证的实施, 使用事件和插件的认证和一个由Phalcon管理的访问控制列表.

登录应用(Log into the Application)

一个 “log in” 功能将允许我们在后台控制器中工作. 后台控制器和前台之前的分离是合乎逻辑的. 所有加载的控制器都位于相同的目录 (app/controllers/).

为了进入系统, 用户必须有一个有效的用户名和密码. 用户存储在数据库 “invo” 里面的 “users” 表里面.

在我们开始会话之前, 我们需要在数据库配置数据库的连接. 一个 “db” 服务在服务容器中设置连接信息. 就自动加载器来说, 我们再一次从配置文件中读取参数来配置一个服务:

<?php

use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

// ...

// 数据库连接是基于配置文件已经定义的参数创建的
$di->set(
    "db",
    function () use ($config) {
        return new DbAdapter(
            [
                "host"     => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname"   => $config->database->name,
            ]
        );
    }
);

这里, 我们将会返回一个MySQL连接适配器的一个实例. 如果需要, 你可以做一些额外的操作比如添加一个日志记录, 一个分析器或者改变适配器, 设置你想要的.

下列表单(app/views/session/index.volt) 请求登录信息. 我们已经删除了一些 HTML 代码来让例子更加简洁:

{{ form("session/start") }}
    <fieldset>
        <div>
            <label for="email">
                Username/Email
            </label>

            <div>
                {{ text_field("email") }}
            </div>
        </div>

        <div>
            <label for="password">
                Password
            </label>

            <div>
                {{ password_field("password") }}
            </div>
        </div>



        <div>
            {{ submit_button("Login") }}
        </div>
    </fieldset>
{{ endForm() }}

使用原生的PHP作为以前的教程, 我们开始使用 Volt. 这是一个内置的模板引擎受 Jinja 的影响而提供简单而又友好的语法来创建模板. 在你熟悉 Volt 之前, 它将不会花费你太多的时间.

SessionController::startAction 方法 (app/controllers/SessionController.php) 有验证表单中输入的数据包括检查在数据库中是否为有效用户的任务:

<?php

class SessionController extends ControllerBase
{
    // ...

    private function _registerSession($user)
    {
        $this->session->set(
            "auth",
            [
                "id"   => $user->id,
                "name" => $user->name,
            ]
        );
    }

    /**
     * 这个方法检验和记录一个用户到应用中
     */
    public function startAction()
    {
        if ($this->request->isPost()) {
            // 从用户获取数据
            $email    = $this->request->getPost("email");
            $password = $this->request->getPost("password");

            // 在数据库中查找用户
            $user = Users::findFirst(
                [
                    "(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
                    "bind" => [
                        "email"    => $email,
                        "password" => sha1($password),
                    ]
                ]
            );

            if ($user !== false) {
                $this->_registerSession($user);

                $this->flash->success(
                    "Welcome " . $user->name
                );

                // 如果用户是有效的, 转发到'invoices'控制器
                return $this->dispatcher->forward(
                    [
                        "controller" => "invoices",
                        "action"     => "index",
                    ]
                );
            }

            $this->flash->error(
                "Wrong email/password"
            );
        }

        // 再一次转发到登录表单
        return $this->dispatcher->forward(
            [
                "controller" => "session",
                "action"     => "index",
            ]
        );
    }
}

为简单起见, 我们使用 “sha1” 在数据库中存储密码散列, 然而, 在实际应用中不建议采用此算法, 使用 “bcrypt” 代替.

请注意, 多个公共属性在控制器访问, 像: $this->flash, $this->request 或者 $this->session. 这些是先前在服务容器中定义的服务 (app/config/services.php). 当它们第一次访问的时候, 它们被注入作为控制器的一部分.

这些服务是”共享”的, 这意味着我们总是访问相同的地方, 无论我们在哪里调用它们.

例如, 这里我们调用 “session” 服务然后我们在变量 “auth” 中存储用户身份:

<?php

$this->session->set(
    "auth",
    [
        "id"   => $user->id,
        "name" => $user->name,
    ]
);

本节的另外一个重要方面是如何验证用户为有效的, 首先我们验证是否使用的是POST请求的:

<?php

if ($this->request->isPost()) {

然后, 我们接收表单中的参数:

<?php

$email    = $this->request->getPost("email");
$password = $this->request->getPost("password");

现在, 我们需要检查是否存在一个相同的用户名或邮箱和密码的用户:

<?php

$user = Users::findFirst(
    [
        "(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
        "bind" => [
            "email"    => $email,
            "password" => sha1($password),
        ]
    ]
);

注意, ‘绑定参数’的使用, 占位符 :email: 和 :password: 要放置在替换的值的位置, 然后值的’绑定’使用参数 ‘bind’. 安全的替换列的值而没有SQL注入的危险.

如果用户是有效的, 我们将会在session中注册它, 并且转发到dashboard:

<?php

if ($user !== false) {
    $this->_registerSession($user);

    $this->flash->success(
        "Welcome " . $user->name
    );

    return $this->dispatcher->forward(
        [
            "controller" => "invoices",
            "action"     => "index",
        ]
    );
}

如果用户不存在,再一次转发到登录表单让用户再次操作:

<?php

return $this->dispatcher->forward(
    [
        "controller" => "session",
        "action"     => "index",
    ]
);
后端安全(Securing the Backend)

后端是一个私有区域,只有已经注册的人可以访问. 因此, 只有注册用户才能访问控制器这样的检验是有必要的. 如果你没有登录到应用中并试图访问, 例如, products 控制器 (这是私有的) 你将会看到如下屏幕:

_images/invo-2.png

每次有人试图访问任何controller/action, 应用将会验证当前角色(在session中)是否能够访问它, 否则就会显示一个像上面那样的消息并转发到首页.

现在, 让我们看看应用程序是如何实现的. 首先我们知道有个组件叫做 Dispatcher. 通过 Routing 组件来找到路由. 然后, 它负责加载合适的控制器和执行相应的动作方法.

正常情况下, 框架会自动创建分发器. 对我们而言, 我们想在执行请求的方法之前执行一个验证, 校验用户是否可以访问它. 要做到这一点, 我们需要在启动文件中创建一个方法来替换组件:

<?php

use Phalcon\Mvc\Dispatcher;

// ...

/**
 * MVC 分发器
 */
$di->set(
    "dispatcher",
    function () {
        // ...

        $dispatcher = new Dispatcher();

        return $dispatcher;
    }
);

我们现在使用完全控制的分发器用于应用程序. 在框架中需要多组件的触发事件, 允许我们能够修改内部的操作流. 依赖注入组件作为胶水的一部分, 一个新的叫做 EventsManager 的组件允许我们拦截由组件产生的事件, 路由事件到监听.

事件管理(Events Management)

一个 EventsManager 允许我们为一个特定类型的事件添加监听. 现在我们感兴趣的类型是 “dispatch”. 下列代码过滤了由分发器产生的所有事件:

<?php

use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理器
        $eventsManager = new EventsManager();

        // 监听分发器中使用安全插件产生的事件
        $eventsManager->attach(
            "dispatch:beforeExecuteRoute",
            new SecurityPlugin()
        );

        // 处理异常和使用 NotFoundPlugin 未找到异常
        $eventsManager->attach(
            "dispatch:beforeException",
            new NotFoundPlugin()
        );

        $dispatcher = new Dispatcher();

        // 分配事件管理器到分发器
        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);

当一个叫做 “beforeExecuteRoute” 的事件触发以下插件将会被通知:

<?php

/**
 * 检验用户是否允许使用 SecurityPlugin 访问某些方法
 */
$eventsManager->attach(
    "dispatch:beforeExecuteRoute",
    new SecurityPlugin()
);

当一个 “beforeException” 被触发然后其他插件通知:

<?php

/**
 * 处理异常和使用 NotFoundPlugin 未找到异常
 */
$eventsManager->attach(
    "dispatch:beforeException",
    new NotFoundPlugin()
);

SecurityPlugin 是一个类位于(app/plugins/SecurityPlugin.php). 这个类实现了 “beforeExecuteRoute” 方法. 这是一个相同的名字在分发器中产生的事件中的一个:

<?php

use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;

class SecurityPlugin extends Plugin
{
    // ...

    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // ...
    }
}

钩子事件始终接收第一个包含上下文信息所产生的事件($event)的参数和第二个包含事件本身所产生的对象($dispatcher)的参数. 这不是一个强制性的插件扩展类 Phalcon\Mvc\User\Plugin, 但通过这样做, 它们更容易获得应用程序中可用的服务.

现在, 我们验证当前 session 中的角色, 验证用户是否可以通过ACL列表访问.如果用户没有权限, 我们将会重定向到如上所述的主页中去:

<?php

use Phalcon\Acl;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;

class SecurityPlugin extends Plugin
{
    // ...

    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // 检查session中是否存在"auth"变量来定义当前活动的角色
        $auth = $this->session->get("auth");

        if (!$auth) {
            $role = "Guests";
        } else {
            $role = "Users";
        }

        // 从分发器获取活动的 controller/action
        $controller = $dispatcher->getControllerName();
        $action     = $dispatcher->getActionName();

        // 获得ACL列表
        $acl = $this->getAcl();

        // 检验角色是否允许访问控制器 (resource)
        $allowed = $acl->isAllowed($role, $controller, $action);

        if (!$allowed) {
            // 如果没有访问权限则转发到 index 控制器
            $this->flash->error(
                "You don't have access to this module"
            );

            $dispatcher->forward(
                [
                    "controller" => "index",
                    "action"     => "index",
                ]
            );

            // 返回 "false" 我们将告诉分发器停止当前操作
            return false;
        }
    }
}
提供 ACL 列表(Providing an ACL list)

在上面的例子中我们已经获得了ACL的使用方法 $this->getAcl(). 这个方法也是在插件中实现的. 现在我们要逐步解释如何建立访问控制列表(ACL):

<?php

use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory as AclList;

// 创建一个 ACL
$acl = new AclList();

// 默认行为是 DENY(拒绝) 访问
$acl->setDefaultAction(
    Acl::DENY
);

// 注册两个角色, 用户是已注册用户和没有定义身份的来宾用户
$roles = [
    "users"  => new Role("Users"),
    "guests" => new Role("Guests"),
];

foreach ($roles as $role) {
    $acl->addRole($role);
}

现在, 我们分别为每个区域定义资源. 控制器名称是资源它们的方法是对资源的访问:

<?php

use Phalcon\Acl\Resource;

// ...

// 私有区域资源 (后台)
$privateResources = [
    "companies"    => ["index", "search", "new", "edit", "save", "create", "delete"],
    "products"     => ["index", "search", "new", "edit", "save", "create", "delete"],
    "producttypes" => ["index", "search", "new", "edit", "save", "create", "delete"],
    "invoices"     => ["index", "profile"],
];

foreach ($privateResources as $resourceName => $actions) {
    $acl->addResource(
        new Resource($resourceName),
        $actions
    );
}

// 公共区域资源 (前台)
$publicResources = [
    "index"    => ["index"],
    "about"    => ["index"],
    "register" => ["index"],
    "errors"   => ["show404", "show500"],
    "session"  => ["index", "register", "start", "end"],
    "contact"  => ["index", "send"],
];

foreach ($publicResources as $resourceName => $actions) {
    $acl->addResource(
        new Resource($resourceName),
        $actions
    );
}

ACL现在了解现有的控制器和它们相关的操作. 角色 “Users” 由权限访问前台和后台的所有资源. 角色 “Guests” 仅允许访问公共区域:

<?php

// 授权user和Grant访问公共区域
foreach ($roles as $role) {
    foreach ($publicResources as $resource => $actions) {
        $acl->allow(
            $role->getName(),
            $resource,
            "*"
        );
    }
}

// 授权仅角色Users 访问私有区域
foreach ($privateResources as $resource => $actions) {
    foreach ($actions as $action) {
        $acl->allow(
            "Users",
            $resource,
            $action
        );
    }
}

万岁!, ACL现在终于完成了. 在下一章, 我们将会看到Phalcon中的CRUD是如何实现的并且你如何自定义它.

教程4: 使用CRUD(Tutorial 4: Working with the CRUD)

后台通常提供表单来允许用户提交数据. 继续对INVO的解释, 我们现在处理CRUD的创建, 一个非常常见的操作任务, Phalcon将会帮助你使用表单, 校验, 分页和更多.

在INVO(公司, 产品和产品类型)中大部分选项操作数据都是使用一个基础的常见的 CRUD (创建, 读取, 更新和删除)开发的. 每个CRUD包含以下文件:

invo/
    app/
        controllers/
            ProductsController.php
        models/
            Products.php
        forms/
            ProductsForm.php
        views/
            products/
                edit.volt
                index.volt
                new.volt
                search.volt

每个控制器都有以下方法:

<?php

class ProductsController extends ControllerBase
{
    /**
     * 开始操作, 它展示"search"视图
     */
    public function indexAction()
    {
        // ...
    }

    /**
     * 基于从"index"发送过来的条件处理"search"
     * 返回一个分页结果
     */
    public function searchAction()
    {
        // ...
    }

    /**
     * 展示创建一个"new"(新)产品的视图
     */
    public function newAction()
    {
        // ...
    }

    /**
     * 展示编辑一个已存在"edit"(编辑)产品的视图
     */
    public function editAction()
    {
        // ...
    }

    /**
     * 基于"new"方法中输入的数据创建一个产品
     */
    public function createAction()
    {
        // ...
    }

    /**
     * 基于"edit"方法中输入的数据更新一个产品
     */
    public function saveAction()
    {
        // ...
    }

    /**
     * 删除一个已存在的产品
     */
    public function deleteAction($id)
    {
        // ...
    }
}
表单搜索(The Search Form)

每个 CRUD 都开始于一个搜索表单. 这个表单展示了表(products)中的每个字段, 允许用户为一些字段创建一个搜索条件. 表 “products” 和表 “products_types” 是关系表. 既然这样, 我们先前查询表中的记录以便于字段的搜索:

<?php

/**
 * 开始操作, 它展示"search"视图
 */
public function indexAction()
{
    $this->persistent->searchParams = null;

    $this->view->form = new ProductsForm();
}

ProductsForm 表单的实例 (app/forms/ProductsForm.php)传递给了视图. 这个表单定义了用户可见的字段:

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Hidden;
use Phalcon\Forms\Element\Select;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Numericality;

class ProductsForm extends Form
{
    /**
     * 初始化产品表单
     */
    public function initialize($entity = null, $options = [])
    {
        if (!isset($options["edit"])) {
            $element = new Text("id");

            $element->setLabel("Id");

            $this->add(
                $element
            );
        } else {
            $this->add(
                new Hidden("id")
            );
        }



        $name = new Text("name");

        $name->setLabel("Name");

        $name->setFilters(
            [
                "striptags",
                "string",
            ]
        );

        $name->addValidators(
            [
                new PresenceOf(
                    [
                        "message" => "Name is required",
                    ]
                )
            ]
        );

        $this->add($name);



        $type = new Select(
            "profilesId",
            ProductTypes::find(),
            [
                "using"      => [
                    "id",
                    "name",
                ],
                "useEmpty"   => true,
                "emptyText"  => "...",
                "emptyValue" => "",
            ]
        );

        $this->add($type);



        $price = new Text("price");

        $price->setLabel("Price");

        $price->setFilters(
            [
                "float",
            ]
        );

        $price->addValidators(
            [
                new PresenceOf(
                    [
                        "message" => "Price is required",
                    ]
                ),
                new Numericality(
                    [
                        "message" => "Price is required",
                    ]
                ),
            ]
        );

        $this->add($price);
    }
}

表单是使用面向对象的方式声明的, 基于 forms 组件提供的元素. 每个元素都遵循近乎相同的结构:

<?php

// 创建一个元素
$name = new Text("name");

// 设置它的label
$name->setLabel("Name");

// 在验证元素之前应用这些过滤器
$name->setFilters(
    [
        "striptags",
        "string",
    ]
);

// 应用此验证
$name->addValidators(
    [
        new PresenceOf(
            [
                "message" => "Name is required",
            ]
        )
    ]
);

// 增加元素到表单
$this->add($name);

在表单中其它元素也是这样使用:

<?php

// 增加一个隐藏input到表单
$this->add(
    new Hidden("id")
);

// ...

$productTypes = ProductTypes::find();

// 增加一个HTML Select (列表) 到表单
// 数据从"product_types"中填充
$type = new Select(
    "profilesId",
    $productTypes,
    [
        "using"      => [
            "id",
            "name",
        ],
        "useEmpty"   => true,
        "emptyText"  => "...",
        "emptyValue" => "",
    ]
);

注意, ProductTypes::find() 包含的必须的数据 使用 Phalcon\Tag::select() 来填充 SELECT 标签. 一旦表单传递给视图, 它会进行渲染并呈现给用户:

{{ form("products/search") }}

    <h2>
        Search products
    </h2>

    <fieldset>

        {% for element in form %}
            <div class="control-group">
                {{ element.label(["class": "control-label"]) }}

                <div class="controls">
                    {{ element }}
                </div>
            </div>
        {% endfor %}



        <div class="control-group">
            {{ submit_button("Search", "class": "btn btn-primary") }}
        </div>

    </fieldset>

{{ endForm() }}

这会生成下面的HTML:

<form action="/invo/products/search" method="post">

    <h2>
        Search products
    </h2>

    <fieldset>

        <div class="control-group">
            <label for="id" class="control-label">Id</label>

            <div class="controls">
                <input type="text" id="id" name="id" />
            </div>
        </div>

        <div class="control-group">
            <label for="name" class="control-label">Name</label>

            <div class="controls">
                <input type="text" id="name" name="name" />
            </div>
        </div>

        <div class="control-group">
            <label for="profilesId" class="control-label">profilesId</label>

            <div class="controls">
                <select id="profilesId" name="profilesId">
                    <option value="">...</option>
                    <option value="1">Vegetables</option>
                    <option value="2">Fruits</option>
                </select>
            </div>
        </div>

        <div class="control-group">
            <label for="price" class="control-label">Price</label>

            <div class="controls">
                <input type="text" id="price" name="price" />
            </div>
        </div>



        <div class="control-group">
            <input type="submit" value="Search" class="btn btn-primary" />
        </div>

    </fieldset>

</form>

当表单提交的时候, 控制器里面的”search”操作是基于用户输入的数据执行搜索的.

创建和更新记录(Creating and Updating Records)

现在, 让我们看看 CRUD 如何创建和更新记录. 从 “new” 和 “edit” 视图, 通过用户输入的数据发送 “create” 和 “save” 方法从而分别执行 “creating” 和 “updating” 产品的方法.

在创建的情况下, 我们提取提交的数据然后分配它们到一个新的 “Products” 实例:

<?php

/**
 * 基于在 "new" 方法中输入的数据创建一个产品
 */
public function createAction()
{
    if (!$this->request->isPost()) {
        return $this->dispatcher->forward(
            [
                "controller" => "products",
                "action"     => "index",
            ]
        );
    }

    $form = new ProductsForm();

    $product = new Products();

    $product->id               = $this->request->getPost("id", "int");
    $product->product_types_id = $this->request->getPost("product_types_id", "int");
    $product->name             = $this->request->getPost("name", "striptags");
    $product->price            = $this->request->getPost("price", "double");
    $product->active           = $this->request->getPost("active");

    // ...
}

还记得我们在产品表单中定义的过滤器吗? 数据在开始分配到 $product 对象前进行过滤. 这个过滤器是可选的; ORM同样也会转义输入的数据和根据列类型执行附加的转换:

<?php

// ...

$name = new Text("name");

$name->setLabel("Name");

// 过滤 name
$name->setFilters(
    [
        "striptags",
        "string",
    ]
);

// 验证 name
$name->addValidators(
    [
        new PresenceOf(
            [
                "message" => "Name is required",
            ]
        )
    ]
);

$this->add($name);

当保存的时候, 我们就会知道 ProductsForm (app/forms/ProductsForm.php) 表单提交的数据是否否则业务规则和实现的验证:

<?php

// ...

$form = new ProductsForm();

$product = new Products();

// V验证输入
$data = $this->request->getPost();

if (!$form->isValid($data, $product)) {
    $messages = $form->getMessages();

    foreach ($messages as $message) {
        $this->flash->error($message);
    }

    return $this->dispatcher->forward(
        [
            "controller" => "products",
            "action"     => "new",
        ]
    );
}

最后, 如果表单没有返回任何验证消息, 我们就可以保存产品实例了:

<?php

// ...

if ($product->save() === false) {
    $messages = $product->getMessages();

    foreach ($messages as $message) {
        $this->flash->error($message);
    }

    return $this->dispatcher->forward(
        [
            "controller" => "products",
            "action"     => "new",
        ]
    );
}

$form->clear();

$this->flash->success(
    "Product was created successfully"
);

return $this->dispatcher->forward(
    [
        "controller" => "products",
        "action"     => "index",
    ]
);

现在, 在更新产品的情况下, 我们必须先将当前编辑的记录展示给用户:

<?php

/**
 * 基于它的id编辑一个产品
 */
public function editAction($id)
{
    if (!$this->request->isPost()) {
        $product = Products::findFirstById($id);

        if (!$product) {
            $this->flash->error(
                "Product was not found"
            );

            return $this->dispatcher->forward(
                [
                    "controller" => "products",
                    "action"     => "index",
                ]
            );
        }

        $this->view->form = new ProductsForm(
            $product,
            [
                "edit" => true,
            ]
        );
    }
}

通过将模型作为第一个参数传递过去找出被绑定到表单的数据. 多亏了这个, 用户可以改变任何值, 然后通过 “save” 方法发送它到数据库:

<?php

/**
 * 在 "edit"方法中基于输入的数据更新一个产品
 */
public function saveAction()
{
    if (!$this->request->isPost()) {
        return $this->dispatcher->forward(
            [
                "controller" => "products",
                "action"     => "index",
            ]
        );
    }

    $id = $this->request->getPost("id", "int");

    $product = Products::findFirstById($id);

    if (!$product) {
        $this->flash->error(
            "Product does not exist"
        );

        return $this->dispatcher->forward(
            [
                "controller" => "products",
                "action"     => "index",
            ]
        );
    }

    $form = new ProductsForm();

    $data = $this->request->getPost();

    if (!$form->isValid($data, $product)) {
        $messages = $form->getMessages();

        foreach ($messages as $message) {
            $this->flash->error($message);
        }

        return $this->dispatcher->forward(
            [
                "controller" => "products",
                "action"     => "new",
            ]
        );
    }

    if ($product->save() === false) {
        $messages = $product->getMessages();

        foreach ($messages as $message) {
            $this->flash->error($message);
        }

        return $this->dispatcher->forward(
            [
                "controller" => "products",
                "action"     => "new",
            ]
        );
    }

    $form->clear();

    $this->flash->success(
        "Product was updated successfully"
    );

    return $this->dispatcher->forward(
        [
            "controller" => "products",
            "action"     => "index",
        ]
    );
}

我们已经看到 Phalcon 如何以一种结构化的方式让你创建表单和从一个数据库中绑定数据. 在下一章, 我们将会看到如何添加自定义 HTML 元素, 比如一个菜单.

教程5: 定制INVO(Tutorial 5: Customizing INVO)

要完成 INVO 的详细说明, 我们将会解释如何自定义 INVO 添加 UI 元素和根据控制器的执行从而改变标题.

用户组件(User Components)

所有的UI元素和应用的视觉效果大部分都是通过 Bootstrap 实现的. 有些元素, 比如根据应用程序的状态而发生的导航条的变化. 例如, 右上角, 如果用户已经登录到应用程序, 链接”Log in / Sign Up” 变为 “Log out”.

应用程序的这部分是用的组件 “Elements” (app/library/Elements.php) 来实现的.

<?php

use Phalcon\Mvc\User\Component;

class Elements extends Component
{
    public function getMenu()
    {
        // ...
    }

    public function getTabs()
    {
        // ...
    }
}

这个类继承 Phalcon\Mvc\User\Component. 这不是强加的去继承这个类的组件, 但是它会帮助我们更加快速的访问呢应用的服务. 现在, 我们将在服务容器中注册沃恩的第一个用户组件:

<?php

// 注册用户组件
$di->set(
    "elements",
    function () {
        return new Elements();
    }
);

作为控制器, 在视图中的插件或者组件, 这个组件还可以已在容器中注册的服务和通过访问一个相同名字的属性作为一个预先注册的服务:

<div class="navbar navbar-fixed-top">
    <div class="navbar-inner">
        <div class="container">
            <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </a>

            <a class="brand" href="#">INVO</a>

            {{ elements.getMenu() }}
        </div>
    </div>
</div>

<div class="container">
    {{ content() }}

    <hr>

    <footer>
        <p>&copy; Company 2015</p>
    </footer>
</div>

重要的部分是:

{{ elements.getMenu() }}
动态改变标题(Changing the Title Dynamically)

当你在不同的选项中浏览的时候就会看到标题在动态的改变. 在每个控制器初始化的时候实现:

<?php

class ProductsController extends ControllerBase
{
    public function initialize()
    {
        // 设置文档标题
        $this->tag->setTitle(
            "Manage your product types"
        );

        parent::initialize();
    }

    // ...
}

注意, 这个方法 parent::initialize() 也被调用, 它添加更多的数据到标题:

<?php

use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{
    protected function initialize()
    {
        // 在标题的前面加上应用名称
        $this->tag->prependTitle(
            "INVO | "
        );
    }

    // ...
}

最后, 标题在 main 视图 (app/views/index.volt) 输出了 :

<!DOCTYPE html>
<html>
    <head>
        <?php echo $this->tag->getTitle(); ?>
    </head>

    <!-- ... -->
</html>

Tutorial 6: Vökuró

Vökuró is another sample application you can use to learn more about Phalcon. Vökuró is a small website that shows how to implement a security features and management of users and permissions. You can clone its code from Github.

Project Structure

Once you clone the project in your document root you’ll see the following structure:

vokuro/
    app/
        config/
        controllers/
        forms/
        library/
        models/
        views/
    cache/
    public/
        css/
        img/
    schemas/

This project follows a quite similar structure to INVO. Once you open the application in your browser http://localhost/vokuro you’ll see something like this:

_images/vokuro-1.png

The application is divided into two parts, a frontend, where visitors can sign up the service and a backend where administrative users can manage registered users. Both frontend and backend are combined in a single module.

Load Classes and Dependencies

This project uses Phalcon\Loader to load controllers, models, forms, etc. within the project and composer to load the project’s dependencies. So, the first thing you have to do before execute Vökuró is install its dependencies via composer. Assuming you have it correctly installed, type the following command in the console:

cd vokuro
composer install

Vökuró sends emails to confirm the sign up of registered users using Swift, the composer.json looks like:

{
    "require" : {
        "php" : ">=5.5.0",
        "ext-phalcon" : ">=3.0.0",
        "swiftmailer/swiftmailer" : "^5.4",
        "amazonwebservices/aws-sdk-for-php" : "~1.0"
    }
}

Now, there is a file called app/config/loader.php where all the auto-loading stuff is set up. At the end of this file you can see that the composer autoloader is included enabling the application to autoload any of the classes in the downloaded dependencies:

<?php

// ...

// Use composer autoloader to load vendor classes
require_once BASE_PATH . "/vendor/autoload.php";

Moreover, Vökuró, unlike the INVO, utilizes namespaces for controllers and models which is the recommended practice to structure a project. This way the autoloader looks slightly different than the one we saw before (app/config/loader.php):

<?php

use Phalcon\Loader;

$loader = new Loader();

$loader->registerNamespaces(
    [
        "Vokuro\\Models"      => $config->application->modelsDir,
        "Vokuro\\Controllers" => $config->application->controllersDir,
        "Vokuro\\Forms"       => $config->application->formsDir,
        "Vokuro"              => $config->application->libraryDir,
    ]
);

$loader->register();

// ...

Instead of using registerDirectories(), we use registerNamespaces(). Every namespace points to a directory defined in the configuration file (app/config/config.php). For instance the namespace Vokuro\Controllers points to app/controllers so all the classes required by the application within this namespace requires it in its definition:

<?php

namespace Vokuro\Controllers;

class AboutController extends ControllerBase
{
    // ...
}
Sign Up

First, let’s check how users are registered in Vökuró. When a user clicks the “Create an Account” button, the controller SessionController is invoked and the action “signup” is executed:

<?php

namespace Vokuro\Controllers;

use Vokuro\Forms\SignUpForm;

class RegisterController extends ControllerBase
{
    public function signupAction()
    {
        $form = new SignUpForm();

        // ...

        $this->view->form = $form;
    }
}

This action simply pass a form instance of SignUpForm to the view, which itself is rendered to allow the user enter the login details:

{{ form("class": "form-search") }}

    <h2>
        Sign Up
    </h2>

    <p>{{ form.label("name") }}</p>
    <p>
        {{ form.render("name") }}
        {{ form.messages("name") }}
    </p>

    <p>{{ form.label("email") }}</p>
    <p>
        {{ form.render("email") }}
        {{ form.messages("email") }}
    </p>

    <p>{{ form.label("password") }}</p>
    <p>
        {{ form.render("password") }}
        {{ form.messages("password") }}
    </p>

    <p>{{ form.label("confirmPassword") }}</p>
    <p>
        {{ form.render("confirmPassword") }}
        {{ form.messages("confirmPassword") }}
    </p>

    <p>
        {{ form.render("terms") }} {{ form.label("terms") }}
        {{ form.messages("terms") }}
    </p>

    <p>{{ form.render("Sign Up") }}</p>

    {{ form.render("csrf", ["value": security.getToken()]) }}
    {{ form.messages("csrf") }}

    <hr>

{{ endForm() }}

教程 7:创建简单的 REST API(Tutorial 7: Creating a Simple REST API)

在这个教程中,我们会学习如何创建一个拥有 RESTful API 的应用程序,它将会使用如下的几个 HTTP 方法:

  • GET - 接受、查找数据
  • POST - 添加数据
  • PUT - 更新数据
  • DELETE - 删除数据
定义 API(Defining the API)

这个 API 包含如下方法(Methods)

Method URL Action
GET /api/robots Retrieves all robots
GET /api/robots/search/Astro Searches for robots with ‘Astro’ in their name
GET /api/robots/2 Retrieves robots based on primary key
POST /api/robots Adds a new robot
PUT /api/robots/2 Updates robots based on primary key
DELETE /api/robots/2 Deletes robots based on primary key
创建应用(Creating the Application)

As the application is so simple, we will not implement any full MVC environment to develop it. In this case, we will use a micro application to meet our goal.

The following file structure is more than enough:

my-rest-api/
    models/
        Robots.php
    index.php
    .htaccess

First, we need an .htaccess file that contains all the rules to rewrite the URIs to the index.php file, that is our application:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

Then, in the index.php file we create the following:

<?php

use Phalcon\Mvc\Micro;

$app = new Micro();

// Define the routes here

$app->handle();

Now we will create the routes as we defined above:

<?php

use Phalcon\Mvc\Micro;

$app = new Micro();

// Retrieves all robots
$app->get(
    "/api/robots",
    function () {

    }
);

// Searches for robots with $name in their name
$app->get(
    "/api/robots/search/{name}",
    function ($name) {

    }
);

// Retrieves robots based on primary key
$app->get(
    "/api/robots/{id:[0-9]+}",
    function ($id) {

    }
);

// Adds a new robot
$app->post(
    "/api/robots",
    function () {

    }
);

// Updates robots based on primary key
$app->put(
    "/api/robots/{id:[0-9]+}",
    function () {

    }
);

// Deletes robots based on primary key
$app->delete(
    "/api/robots/{id:[0-9]+}",
    function () {

    }
);

$app->handle();

Each route is defined with a method with the same name as the HTTP method, as first parameter we pass a route pattern, followed by a handler. In this case, the handler is an anonymous function. The following route: '/api/robots/{id:[0-9]+}', by example, explicitly sets that the “id” parameter must have a numeric format.

When a defined route matches the requested URI then the application executes the corresponding handler.

创建模型(Creating a Model)

Our API provides information about ‘robots’, these data are stored in a database. The following model allows us to access that table in an object-oriented way. We have implemented some business rules using built-in validators and simple validations. Doing this will give us the peace of mind that saved data meet the requirements of our application:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Message;
use Phalcon\Mvc\Model\Validator\Uniqueness;
use Phalcon\Mvc\Model\Validator\InclusionIn;

class Robots extends Model
{
    public function validation()
    {
        // Type must be: droid, mechanical or virtual
        $this->validate(
            new InclusionIn(
                [
                    "field"  => "type",
                    "domain" => [
                        "droid",
                        "mechanical",
                        "virtual",
                    ]
                )
            )
        );

        // Robot name must be unique
        $this->validate(
            new Uniqueness(
                [
                    "field"   => "name",
                    "message" => "The robot name must be unique",
                ]
            )
        );

        // Year cannot be less than zero
        if ($this->year < 0) {
            $this->appendMessage(
                new Message("The year cannot be less than zero")
            );
        }

        // Check if any messages have been produced
        if ($this->validationHasFailed() === true) {
            return false;
        }
    }
}

Now, we must set up a connection to be used by this model and load it within our app:

<?php

use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;

// Use Loader() to autoload our model
$loader = new Loader();

$loader->registerNamespaces(
    [
        "Store\\Toys" => __DIR__ . "/models/",
    ]
);

$loader->register();

$di = new FactoryDefault();

// Set up the database service
$di->set(
    "db",
    function () {
        return new PdoMysql(
            [
                "host"     => "localhost",
                "username" => "asimov",
                "password" => "zeroth",
                "dbname"   => "robotics",
            ]
        );
    }
);

// Create and bind the DI to the application
$app = new Micro($di);
检索数据(Retrieving Data)

The first “handler” that we will implement is which by method GET returns all available robots. Let’s use PHQL to perform this simple query returning the results as JSON:

<?php

// Retrieves all robots
$app->get(
    "/api/robots",
    function () use ($app) {
        $phql = "SELECT * FROM Store\\Toys\\Robots ORDER BY name";

        $robots = $app->modelsManager->executeQuery($phql);

        $data = [];

        foreach ($robots as $robot) {
            $data[] = [
                "id"   => $robot->id,
                "name" => $robot->name,
            ];
        }

        echo json_encode($data);
    }
);

PHQL, allow us to write queries using a high-level, object-oriented SQL dialect that internally translates to the right SQL statements depending on the database system we are using. The clause “use” in the anonymous function allows us to pass some variables from the global to local scope easily.

The searching by name handler would look like:

<?php

// Searches for robots with $name in their name
$app->get(
    "/api/robots/search/{name}",
    function ($name) use ($app) {
        $phql = "SELECT * FROM Store\\Toys\\Robots WHERE name LIKE :name: ORDER BY name";

        $robots = $app->modelsManager->executeQuery(
            $phql,
            [
                "name" => "%" . $name . "%"
            ]
        );

        $data = [];

        foreach ($robots as $robot) {
            $data[] = [
                "id"   => $robot->id,
                "name" => $robot->name,
            ];
        }

        echo json_encode($data);
    }
);

Searching by the field “id” it’s quite similar, in this case, we’re also notifying if the robot was found or not:

<?php

use Phalcon\Http\Response;

// Retrieves robots based on primary key
$app->get(
    "/api/robots/{id:[0-9]+}",
    function ($id) use ($app) {
        $phql = "SELECT * FROM Store\\Toys\\Robots WHERE id = :id:";

        $robot = $app->modelsManager->executeQuery(
            $phql,
            [
                "id" => $id,
            ]
        )->getFirst();



        // Create a response
        $response = new Response();

        if ($robot === false) {
            $response->setJsonContent(
                [
                    "status" => "NOT-FOUND"
                ]
            );
        } else {
            $response->setJsonContent(
                [
                    "status" => "FOUND",
                    "data"   => [
                        "id"   => $robot->id,
                        "name" => $robot->name
                    ]
                ]
            );
        }

        return $response;
    }
);
插入数据(Inserting Data)

Taking the data as a JSON string inserted in the body of the request, we also use PHQL for insertion:

<?php

use Phalcon\Http\Response;

// Adds a new robot
$app->post(
    "/api/robots",
    function () use ($app) {
        $robot = $app->request->getJsonRawBody();

        $phql = "INSERT INTO Store\\Toys\\Robots (name, type, year) VALUES (:name:, :type:, :year:)";

        $status = $app->modelsManager->executeQuery(
            $phql,
            [
                "name" => $robot->name,
                "type" => $robot->type,
                "year" => $robot->year,
            ]
        );

        // Create a response
        $response = new Response();

        // Check if the insertion was successful
        if ($status->success() === true) {
            // Change the HTTP status
            $response->setStatusCode(201, "Created");

            $robot->id = $status->getModel()->id;

            $response->setJsonContent(
                [
                    "status" => "OK",
                    "data"   => $robot,
                ]
            );
        } else {
            // Change the HTTP status
            $response->setStatusCode(409, "Conflict");

            // Send errors to the client
            $errors = [];

            foreach ($status->getMessages() as $message) {
                $errors[] = $message->getMessage();
            }

            $response->setJsonContent(
                [
                    "status"   => "ERROR",
                    "messages" => $errors,
                ]
            );
        }

        return $response;
    }
);
更新数据(Updating Data)

The data update is similar to insertion. The “id” passed as parameter indicates what robot must be updated:

<?php

use Phalcon\Http\Response;

// Updates robots based on primary key
$app->put(
    "/api/robots/{id:[0-9]+}",
    function ($id) use ($app) {
        $robot = $app->request->getJsonRawBody();

        $phql = "UPDATE Store\\Toys\\Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";

        $status = $app->modelsManager->executeQuery(
            $phql,
            [
                "id"   => $id,
                "name" => $robot->name,
                "type" => $robot->type,
                "year" => $robot->year,
            ]
        );

        // Create a response
        $response = new Response();

        // Check if the insertion was successful
        if ($status->success() === true) {
            $response->setJsonContent(
                [
                    "status" => "OK"
                ]
            );
        } else {
            // Change the HTTP status
            $response->setStatusCode(409, "Conflict");

            $errors = [];

            foreach ($status->getMessages() as $message) {
                $errors[] = $message->getMessage();
            }

            $response->setJsonContent(
                [
                    "status"   => "ERROR",
                    "messages" => $errors,
                ]
            );
        }

        return $response;
    }
);
删除数据(Deleting Data)

The data delete is similar to update. The “id” passed as parameter indicates what robot must be deleted:

<?php

use Phalcon\Http\Response;

// Deletes robots based on primary key
$app->delete(
    "/api/robots/{id:[0-9]+}",
    function ($id) use ($app) {
        $phql = "DELETE FROM Store\\Toys\\Robots WHERE id = :id:";

        $status = $app->modelsManager->executeQuery(
            $phql,
            [
                "id" => $id,
            ]
        );

        // Create a response
        $response = new Response();

        if ($status->success() === true) {
            $response->setJsonContent(
                [
                    "status" => "OK"
                ]
            );
        } else {
            // Change the HTTP status
            $response->setStatusCode(409, "Conflict");

            $errors = [];

            foreach ($status->getMessages() as $message) {
                $errors[] = $message->getMessage();
            }

            $response->setJsonContent(
                [
                    "status"   => "ERROR",
                    "messages" => $errors,
                ]
            );
        }

        return $response;
    }
);
测试应用(Testing our Application)

Using curl we’ll test every route in our application verifying its proper operation.

Obtain all the robots:

curl -i -X GET http://localhost/my-rest-api/api/robots

HTTP/1.1 200 OK
Date: Tue, 21 Jul 2015 07:05:13 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 117
Content-Type: text/html; charset=UTF-8

[{"id":"1","name":"Robotina"},{"id":"2","name":"Astro Boy"},{"id":"3","name":"Terminator"}]

Search a robot by its name:

curl -i -X GET http://localhost/my-rest-api/api/robots/search/Astro

HTTP/1.1 200 OK
Date: Tue, 21 Jul 2015 07:09:23 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 31
Content-Type: text/html; charset=UTF-8

[{"id":"2","name":"Astro Boy"}]

Obtain a robot by its id:

curl -i -X GET http://localhost/my-rest-api/api/robots/3

HTTP/1.1 200 OK
Date: Tue, 21 Jul 2015 07:12:18 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 56
Content-Type: text/html; charset=UTF-8

{"status":"FOUND","data":{"id":"3","name":"Terminator"}}

Insert a new robot:

curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}'
    http://localhost/my-rest-api/api/robots

HTTP/1.1 201 Created
Date: Tue, 21 Jul 2015 07:15:09 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 75
Content-Type: text/html; charset=UTF-8

{"status":"OK","data":{"name":"C-3PO","type":"droid","year":1977,"id":"4"}}

Try to insert a new robot with the name of an existing robot:

curl -i -X POST -d '{"name":"C-3PO","type":"droid","year":1977}'
    http://localhost/my-rest-api/api/robots

HTTP/1.1 409 Conflict
Date: Tue, 21 Jul 2015 07:18:28 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 63
Content-Type: text/html; charset=UTF-8

{"status":"ERROR","messages":["The robot name must be unique"]}

Or update a robot with an unknown type:

curl -i -X PUT -d '{"name":"ASIMO","type":"humanoid","year":2000}'
    http://localhost/my-rest-api/api/robots/4

HTTP/1.1 409 Conflict
Date: Tue, 21 Jul 2015 08:48:01 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 104
Content-Type: text/html; charset=UTF-8

{"status":"ERROR","messages":["Value of field 'type' must be part of
    list: droid, mechanical, virtual"]}

Finally, delete a robot:

curl -i -X DELETE http://localhost/my-rest-api/api/robots/4

HTTP/1.1 200 OK
Date: Tue, 21 Jul 2015 08:49:29 GMT
Server: Apache/2.2.22 (Unix) DAV/2
Content-Length: 15
Content-Type: text/html; charset=UTF-8

{"status":"OK"}
结束语(Conclusion)

As we have seen, develop a RESTful API with Phalcon is easy. Later in the documentation we’ll explain in detail how to use micro applications and the PHQL language.

组件

依赖注入与服务定位器(Dependency Injection/Service Location)

Phalcon\Di 是一个实现依赖注入和定位服务的组件,而且它本身就是一个装载它们的容器。

因为Phalcon是高度解构的,整合框架的不同组件,使用 Phalcon\Di 是必不可少的。开发者也可以使用这个组件去注入依赖和管理的应用程序中来自不同类的全局实例。

基本上,这个组件实现了 [控制反转](http://zh.wikipedia.org/wiki/%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC) 的模式。使用这种模式,组件的对象不用再使用setter或者构造函数去接受依赖实例,而是使用请求服务的依赖注入。这减少了总的复杂性,因为在组件内,只有一个方法去获取所需的依赖实例。

另外,该模式增加了代码的可测试性,从而使其不易出错。

使用容器注册服务(Registering services in the Container)

框架本身或者开发者都可以注册服务。当一个组件A需要组件B(或者它的类的实例) 去操作,它可以通过容器去请求组件B,而不是创建一个新的组件B实例。

这个工作方法给我们提供了许多优势:

  • 我们可以很容易的使用一个我们自己建立的或者是第三方的组件去替换原有的组件。
  • 我们完全控制对象的初始化,这让我们在传递它们的实例到组件之前,根据需要设置这些对象。
  • 我们可以在一个结构化的和统一组件内获取全局实例。

服务可以使用不同方式去定义:

简单的注册(Simple Registration)

就像你之前看到的那样,这里有几种方法去注册服务。下面是简单调用的例子:

字符串(String)

使用字符串注册服务需要一个有效的类名称,它将返回指定的类对象,如果类还没有加载的话,将使用自动加载器实例化对象。这种类型不允许向构造函数指定参数:

<?php

// 返回 new Phalcon\Http\Request(); 对象
$di->set(
    "request",
    "Phalcon\\Http\\Request"
);
对象(Object)

这种类型注册服务需要一个对象。实际上,这个服务不再需要初始化,因为它已经是一个对象,可以说,这是不是一个真正的依赖注入,但是如果你想强制总是返回相同的对象/值,使用这种方式还是有用的:

<?php

use Phalcon\Http\Request;

// 返回 Phalcon\Http\Request(); 对象
$di->set(
    "request",
    new Request()
);
闭包与匿名函数(Closures/Anonymous functions)

这个方法提供了更加自由的方式去注册依赖,但是如果你想从外部改变实例化的参数而不用改变注册服务的代码,这是很困难的:

<?php

use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;

$di->set(
    "db",
    function () {
        return new PdoMysql(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "blog",
            ]
        );
    }
);

这些限制是可以克服的,通过传递额外的变量到闭包函数里面:

<?php

use Phalcon\Config;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;

$config = new Config(
    [
        "host"     => "127.0.0.1",
        "username" => "user",
        "password" => "pass",
        "dbname"   => "my_database",
    ]
);

// 把当前域的$config变量传递给匿名函数使用
$di->set(
    "db",
    function () use ($config) {
        return new PdoMysql(
            [
                "host"     => $config->host,
                "username" => $config->username,
                "password" => $config->password,
                "dbname"   => $config->name,
            ]
        );
    }
);

You can also access other DI services using the get() method:

<?php

use Phalcon\Config;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;

$di->set(
    "config",
    function () {
        return new Config(
            [
                "host"     => "127.0.0.1",
                "username" => "user",
                "password" => "pass",
                "dbname"   => "my_database",
            ]
        );
    }
);

// Using the 'config' service from the DI
$di->set(
    "db",
    function () {
        $config = $this->get("config");

        return new PdoMysql(
            [
                "host"     => $config->host,
                "username" => $config->username,
                "password" => $config->password,
                "dbname"   => $config->name,
            ]
        );
    }
);
复杂的注册(Complex Registration)

如果要求不用实例化/解析服务,就可以改变定义服务的话,我们需要使用数组的方式去定义服务。使用数组去定义服务可以更加详细:

<?php

use Phalcon\Logger\Adapter\File as LoggerFile;

// 通过类名和参数,注册logger服务
$di->set(
    "logger",
    [
        "className" => "Phalcon\\Logger\\Adapter\\File",
        "arguments" => [
            [
                "type"  => "parameter",
                "value" => "../apps/logs/error.log",
            ]
        ]
    ]
);

// 使用匿名函数的方式
$di->set(
    "logger",
    function () {
        return new LoggerFile("../apps/logs/error.log");
    }
);

上面两种注册服务的方式的结果是一样的。然而,使用数组定义的话,在需要的时候可以变更注册服务的参数:

<?php

// 改变logger服务的类名
$di->getService("logger")->setClassName("MyCustomLogger");

// 不用实例化就可以改变第一个参数值
$di->getService("logger")->setParameter(
    0,
    [
        "type"  => "parameter",
        "value" => "../apps/logs/error.log",
    ]
);

除了使用数组的语法注册服务,你还可以使用以下三种类型的依赖注入:

构造函数注入(Constructor Injection)

这个注入方式是通过传递依赖/参数到类的构造函数。让我们假设我们有下面的组件:

<?php

namespace SomeApp;

use Phalcon\Http\Response;

class SomeComponent
{
    /**
     * @var Response
     */
    protected $_response;

    protected $_someFlag;



    public function __construct(Response $response, $someFlag)
    {
        $this->_response = $response;
        $this->_someFlag = $someFlag;
    }
}

这个服务可以这样被注入:

<?php

$di->set(
    "response",
    [
        "className" => "Phalcon\\Http\\Response"
    ]
);

$di->set(
    "someComponent",
    [
        "className" => "SomeApp\\SomeComponent",
        "arguments" => [
            [
                "type" => "service",
                "name" => "response",
            ],
            [
                "type"  => "parameter",
                "value" => true,
            ],
        ]
    ]
);

reponse服务(Phalcon\Http\Response)作为第一个参数传递给构造函数,与此同时,一个布尔类型的值(true)作为第二个参数传递。

设值注入(Setter Injection)

类中可能有setter去注入可选的依赖,前面那个class可以修改成通过setter来注入依赖的方式:

<?php

namespace SomeApp;

use Phalcon\Http\Response;

class SomeComponent
{
    /**
     * @var Response
     */
    protected $_response;

    protected $_someFlag;



    public function setResponse(Response $response)
    {
        $this->_response = $response;
    }

    public function setFlag($someFlag)
    {
        $this->_someFlag = $someFlag;
    }
}

用setter方式来注入的服务可以通过下面的方式来注册:

<?php

$di->set(
    "response",
    [
        "className" => "Phalcon\\Http\\Response",
    ]
);

$di->set(
    "someComponent",
    [
        "className" => "SomeApp\\SomeComponent",
        "calls"     => [
            [
                "method"    => "setResponse",
                "arguments" => [
                    [
                        "type" => "service",
                        "name" => "response",
                    ]
                ]
            ],
            [
                "method"    => "setFlag",
                "arguments" => [
                    [
                        "type"  => "parameter",
                        "value" => true,
                    ]
                ]
            ]
        ]
    ]
);
属性注入(Properties Injection)

这是一个不太常用的方式,这种方式的注入是通过类的public属性来注入:

<?php

namespace SomeApp;

use Phalcon\Http\Response;

class SomeComponent
{
    /**
     * @var Response
     */
    public $response;

    public $someFlag;
}

通过属性注入的服务,可以像下面这样注册:

<?php

$di->set(
    "response",
    [
        "className" => "Phalcon\\Http\\Response",
    ]
);

$di->set(
    "someComponent",
    [
        "className"  => "SomeApp\\SomeComponent",
        "properties" => [
            [
                "name"  => "response",
                "value" => [
                    "type" => "service",
                    "name" => "response",
                ],
            ],
            [
                "name"  => "someFlag",
                "value" => [
                    "type"  => "parameter",
                    "value" => true,
                ],
            ]
        ]
    ]
);

支持包括下面的参数类型:

Type 描述 例子
parameter 表示一个文本值作为参数传递过去 ["type" => "parameter", "value" => 1234]
service 表示作为服务 ["type" => "service", "name" => "request"]
instance 表示必须动态生成的对象 ["type" => "instance", "className" => "DateTime", "arguments" => ["now"]]

解析一个定义复杂的服务也许性能上稍微慢于先前看到的简单定义。但是,这提供了一个更强大的方式来定义和注入服务。

混合不同类型的定义是可以的,每个人可以应用需要决定什么样的注册服务的方式是最适当的。

Array Syntax

使用数组的方式去注册服务也是可以的:

<?php

use Phalcon\Di;
use Phalcon\Http\Request;

// 创建一个依赖注入容器
$di = new Di();

// 通过类名称设置服务
$di["request"] = "Phalcon\\Http\\Request";

// 使用匿名函数去设置服务,这个实例将被延迟加载
$di["request"] = function () {
    return new Request();
};

// 直接注册一个实例
$di["request"] = new Request();

// 使用数组方式定义服务
$di["request"] = [
    "className" => "Phalcon\\Http\\Request",
];

在上面的例子中,当框架需要访问request服务的内容,它会在容器里面查找名为‘request’的服务。 在容器中将返回所需要的服务的实例。当有需要时,开发者可能最终需要替换这个组件。

每个方法(在上面的例子证明)用于设置/注册服务方面具都具有优势和劣势。这是由开发者和特别的要求决定具体使用哪个。

通过字符串设置一个服务是很简单,但是缺乏灵活性。通过数组设置服务提供了更加灵活的方式,但是使代码更复杂。匿名函数是上述两者之间的一个很好的平衡,但是会导致比预期的更多维护。

Phalcon\Di 对每个储存的服务提供了延迟加载。除非开发者选择直接实例化一个对象并将其存储在容器中,任何储存在里面的对象(通过数组,字符串等等设置的)都将延迟加载,即只要当使用到时才实例化。

服务解疑(Resolving Services)

从容器中获取一个服务是一件简单的事情,只要通过“get”方法就可以。这将返回一个服务的新实例:

<?php $request = $di->get("request");

或者通过魔术方法的方式获取:

<?php

$request = $di->getRequest();

或者通过访问数组的方式获取:

<?php

$request = $di["request"];

参数可以传递到构造函数中,通过添加一个数组的参数到get方法中:

<?php

// 将返回:new MyComponent("some-parameter", "other")
$component = $di->get(
    "MyComponent",
    [
        "some-parameter",
        "other",
    ]
);
Events

Phalcon\Di is able to send events to an EventsManager if it is present. Events are triggered using the type “di”. Some events when returning boolean false could stop the active operation. The following events are supported:

Event Name Triggered Can stop operation? Triggered on
beforeServiceResolve Triggered before resolve service. Listeners receive the service name and the parameters passed to it. No Listeners
afterServiceResolve Triggered after resolve service. Listeners receive the service name, instance, and the parameters passed to it. No Listeners
共享服务(Shared services)

服务可以注册成“shared”类型的服务,这意味着这个服务将使用 [单例模式](http://zh.wikipedia.org/wiki/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F) 运行, 一旦服务被首次解析后,这个实例将被保存在容器中,之后的每次请求都在容器中查找并返回这个实例

<?php

use Phalcon\Session\Adapter\Files as SessionFiles;

// 把session服务注册成“shared”类型
$di->setShared(
    "session",
    function () {
        $session = new SessionFiles();

        $session->start();

        return $session;
    }
);

// 第一次获取session服务时,session服务将实例化
$session = $di->get("session");

// 第二次获取时,不再实例化,直接返回第一次实例化的对象
$session = $di->getSession();

另一种方式去注册一个“shared”类型的服务是,传递“set”服务的时候,把true作为第三个参数传递过去:

<?php

// 把session服务注册成“shared”类型
$di->set(
    "session",
    function () {
        // ...
    },
    true
);

如果一个服务不是注册成“shared”类型,而你又想从DI中获取服务的“shared”实例,你可以使用getShared方法:

<?php

$request = $di->getShared("request");
单独操作服务(Manipulating services individually)

一旦服务被注册到服务容器中,你可以单独操作它:

<?php

use Phalcon\Http\Request;

// 注册request服务
$di->set("request", "Phalcon\\Http\\Request");

// 获取服务
$requestService = $di->getService("request");

// 改变它的定义
$requestService->setDefinition(
    function () {
        return new Request();
    }
);

// 修改成shared类型
$requestService->setShared(true);

// 解析服务(返回Phalcon\Http\Request实例)
$request = $requestService->resolve();
通过服务容器实例化类(Instantiating classes via the Service Container)

当你从服务容器中请求一个服务,如果找不到具有相同名称的服务,它将尝试去加载以这个服务为名称的类。利用这个的行为, 我们可以代替任意一个类,通过简单的利用服务的名称来注册:

<?php

// 把一个控制器注册为服务
$di->set(
    "IndexController",
    function () {
        $component = new Component();

        return $component;
    },
    true
);

// 把一个控制器注册为服务
$di->set(
    "MyOtherComponent",
    function () {
        // 实际上返回另外一个组件
        $component = new AnotherComponent();

        return $component;
    }
);

// 获取通过服务容器创建的对象
$myComponent = $di->get("MyOtherComponent");

你可以利用这种方式,通过服务容器来总是实例化你的类(即是他们没有注册为服务), DI会回退到一个有效的自动加载类中,去加载这个类。通过这样做,以后你可以轻松替换任意的类通过为它实现一个定义。

自动注入 DI(Automatic Injecting of the DI itself)

如果一个类或者组件需要用到DI服务,你需要在你的类中实现 Phalcon\Di\InjectionAwareInterface 接口, 这样就可以在实例化这个类的对象时自动注入DI的服务:

<?php

use Phalcon\DiInterface;
use Phalcon\Di\InjectionAwareInterface;

class MyClass implements InjectionAwareInterface
{
    /**
     * @var DiInterface
     */
    protected $_di;



    public function setDi(DiInterface $di)
    {
        $this->_di = $di;
    }

    public function getDi()
    {
        return $this->_di;
    }
}

按照上面这样,一旦服务被解析,$di 对象将自动传递到 setDi() 方法:

<?php

// 注册服务
$di->set("myClass", "MyClass");

// 解析服务(注意:将自动调用$myClass->setDi($di)方法)
$myClass = $di->get("myClass");
使用文件组织服务(Organizing services in files)

你可以更好的组织你的应用,通过移动注册的服务到独立的文件里面,而不是全部写在应用的引导文件中:

<?php

$di->set(
    "router",
    function () {
        return include "../app/config/routes.php";
    }
);

这样,在文件(”../app/config/routes.php”)中,返回已解析的对象:

<?php

$router = new MyRouter();

$router->post("/login");

return $router;
使用静态的方式访问注入器(Accessing the DI in a static way)

如果需要的话,你可以访问最新创建的DI对象,通过下面这种静态方法的方式:

<?php

use Phalcon\Di;

class SomeComponent
{
    public static function someMethod()
    {
        // 获取session服务
        $session = Di::getDefault()->getSession();
    }
}
注入器默认工厂(Factory Default DI)

尽管Phalcon的解耦性质为我们提供了很大的自由度和灵活性,也许我们只是单纯的想使用它作为一个全栈框架。 为了达到这点,框架提供了变种的 Phalcon\DiPhalcon\Di\FactoryDefault 。这个类会自动注册相应的服务,并捆绑在一起作为一个全栈框架。

<?php

use Phalcon\Di\FactoryDefault;

$di = new FactoryDefault();
服务名称约定(Service Name Conventions)

尽管你可以用你喜欢的名字来注册服务,但是Phalcon有一些命名约定,这些约定让你在需要的时候,可以获得正确的(内置)服务。

服务名称 介绍 默认 是否是shared服务
dispatcher 控制器调度服务 Phalcon\Mvc\Dispatcher
router 路由服务 Phalcon\Mvc\Router
url URL生成服务 Phalcon\Mvc\Url
request HTTP 请求环境服务 Phalcon\Http\Request
response HTTP响应环境服务 Phalcon\Http\Response
cookies HTTP Cookie管理服务 Phalcon\Http\Response\Cookies
filter 输入过滤服务 Phalcon\Filter
flash 闪现信息服务 Phalcon\Flash\Direct
flashSession 闪现session信息服务 Phalcon\Flash\Session
session session服务 Phalcon\Session\Adapter\Files
eventsManager 事件管理服务 Phalcon\Events\Manager
db 底层数据库连接服务 Phalcon\Db
security 安全助手 Phalcon\Security
crypt 加密/解密数据 Phalcon\Crypt
tag HTML生成助手 Phalcon\Tag
escaper 内容(HTML)转义 Phalcon\Escaper
annotations 注释分析器 Phalcon\Annotations\Adapter\Memory
modelsManager model管理服务 Phalcon\Mvc\Model\Manager
modelsMetadata model元数据服务 Phalcon\Mvc\Model\MetaData\Memory
transactionManager model事务管理服务 Phalcon\Mvc\Model\Transaction\Manager
modelsCache model的缓存服务 None No
viewsCache view的缓存服务 None No
自定义注入器(Implementing your own DI)

如果你要创建一个自定义注入器或者继承一个已有的,接口 Phalcon\DiInterface 必须被实现。

MVC 架构(The MVC Architecture)

Phalcon 提供了面向对象的类,在应用程序中必须实现模型(Model)、视图(View)、控制器(Controller)架构(通常我们称之为 MVC)。这种设计模式被广泛的应用到其他 web 框架以及桌面应用程序中。

MVC 优点:

  • 隔离业务逻辑、用户界面和数据库层
  • 不同类型的代码之间更加明确易于维护。

如果你决定使用MVC架构来开发你的程序,那么应用程序的每个请求都将采用 MVC 架构的方式来管理。 Phalcon 的类是使用 C 语言编写而成, 这是为这种模式开发的 PHP 应用程序提供高性能的方法。

模型(Models)

模型代表了应用程序中的信息(数据)和处理数据的规则。模型主要用于管理与相应数据库表进行交互的规则。 大多数情况中,在应用程序中,数据库中每个表将对应一个模型。 应用程序中的大部分业务逻辑都将集中在模型里。 了解更多

视图(Views)

视图代表了应用程序中的用户界面. 视图通常是在 HTML 文件里嵌入 PHP 代码,这些代码仅仅是用来展示数据。 视图的任务是当应用程序发生请求时,提供数据给 web 浏览器或者其他工具。了解更多

控制器(Controllers)

控制器用于控制应用程序的流程,调用模型和视图。负责处理来自 web 浏览器的请求,从模型中获取数据,然后将数据传递给视图完成展示。了解更多

使用控制器(Using Controllers)

控制器提供了一堆可以被调用的方法,即:action。action是控制器中用于处理请求的方法。默认情况下,全部 控制器public的方法都会映射到action并且可以通过URL访问。action负责解释请求和创建响应。 通常,响应是以渲染的视图格式被创建,但也存在其他的方式来创建(译者注:如AJAX请求返回JSON格式的数据)。

例如,当你访问一个类似这样的URL时:http://localhost/blog/posts/show/2015/the-post-title,Phalcon默认会这样分解各个部分:

Phalcon目录 blog
控制器 posts
Action show
参数 2015
参数 the-post-title

这时,PostsController将会处理这个请求。在一个项目中,没有强制指定放置控制器的地方,这些控制器都可以 通过使用 autoloaders 来加载,所以你可以根据需要自由组件你的控制器。

控制器类必须以“Controller”为后缀,action则须以“Action”为后缀。一个控制器类的例子如下:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction($year, $postTitle)
    {

    }
}

额外的URI参数定义为action的参数,以致这些参数可以简单地通过本地变量来获取。控制器 可以选择继承 Phalcon\Mvc\Controller 。如果继承此基类,你的控制器类则能 轻松访问应用的各种服务。

没有默认缺省值的参数视为必须参数处理。可以像PHP那样为参数设定一个默认值:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction($year = 2015, $postTitle = "some default title")
    {

    }
}

参数将会按路由传递和函数定义一样的顺序来赋值。你可以使用以下根据参数名称的方式来获取任意一个参数:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction()
    {
        $year      = $this->dispatcher->getParam("year");
        $postTitle = $this->dispatcher->getParam("postTitle");
    }
}
循环调度(Dispatch Loop)

循环调度将会在分发器执行,直到没有action需要执行为止。在上面的例子中,只有一个action 被执行到。现在让我们来看下:code:`forward()``(转发)怎样才能在循环调度里提供一个更加复杂的操作流,从而将执行转发到 另一个controller/action。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction($year, $postTitle)
    {
        $this->flash->error(
            "You don't have permission to access this area"
        );

        // Forward flow to another action
        $this->dispatcher->forward(
            [
                "controller" => "users",
                "action"     => "signin",
            ]
        );
    }
}

如果用户没有访问某个action的权限,那么请求将会被转发到Users控制器的signin行为。

<?php

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function indexAction()
    {

    }

    public function signinAction()
    {

    }
}

对于“forwards”转发的次数没有限制,只要不会形成循环重定向即可,否则就意味着 你的应用将会停止(译者注:如果浏览器发现一个请求循环重定向时,会终止请求)。 如果在循环调度里面没有其他action可以分发,分发器将会自动调用由 Phalcon\Mvc\View 管理的MVC的视图层。

初始化控制器(Initializing Controllers)

Phalcon\Mvc\Controller 提供了初始化的函数,它会最先执行,并优于任何控制器 的其他action。不推荐使用“__construct”方法。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public $settings;

    public function initialize()
    {
        $this->settings = [
            "mySetting" => "value",
        ];
    }

    public function saveAction()
    {
        if ($this->settings["mySetting"] === "value") {
            // ...
        }
    }
}
initialize() 仅仅会在事件“beforeExecuteRoute”成功执行后才会被调用。这样可以避免 在初始化中的应用逻辑在未鉴权的情况下无法执行。

如果你想在紧接着创建控制器对象的后面执行一些初始化的逻辑,你要实现:code:onConstruct()”方法:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function onConstruct()
    {
        // ...
    }
}
需要注意的是,即使待执行的action在控制器不存在,或者用户没有 访问到它(根据开发人员提供的自定义控制器接入),“onConstruct”都会被执行。
注入服务(Injecting Services)

如果控制器继承于 Phalcon\Mvc\Controller ,那么它可以轻松访问 应用的服务容器。例如,如果我们类似这样注册了一个服务:

<?php

use Phalcon\Di;

$di = new Di();

$di->set(
    "storage",
    function () {
        return new Storage(
            "/some/directory"
        );
    },
    true
);

那么,我们可以通常多种方式来访问这个服务:

<?php

use Phalcon\Mvc\Controller;

class FilesController extends Controller
{
    public function saveAction()
    {
        // 以和服务相同名字的类属性访问
        $this->storage->save("/some/file");

        // 通过DI访问服务
        $this->di->get("storage")->save("/some/file");

        // 另一种方式:使用魔法getter来访问
        $this->di->getStorage()->save("/some/file");

        // 另一种方式:使用魔法getter来访问
        $this->getDi()->getStorage()->save("/some/file");

        // 使用数组下标
        $this->di["storage"]->save("/some/file");
    }
}

如果你是把Phalcon作为全能(Full-Stack)框架来使用,你可以阅读框架中 by default 提供的服务。

请求与响应(Request and Response)

假设框架预先提供了一系列的注册的服务。我们这里将解释如何和HTTP环境进行关联和交互。 “request”服务包含了一个 Phalcon\Http\Request 的实例, “response”服务则包含了一个 Phalcon\Http\Response 的实例,用来表示将要返回给客户端的内容。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // 检查请求是否为POST
        if ($this->request->isPost()) {
            // 获取POST数据
            $customerName = $this->request->getPost("name");
            $customerBorn = $this->request->getPost("born");
        }
    }
}

响应对象通常不会直接使用,但在action的执行前会被创建,有时候 - 如在 一个afterDispatch事件中 - 它对于直接访问响应非常有帮助:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function notFoundAction()
    {
        // 发送一个HTTP 404 响应的header
        $this->response->setStatusCode(404, "Not Found");
    }
}

如需学习了解HTTP环境更多内容,请查看专题: requestresponse

会话数据(Session Data)

会话可以帮助我们在多个请求中保持持久化的数据。你可以从任何控制器中访问 Phalcon\Session\Bag 以便封装需要进行持久化的数据。

<?php

use Phalcon\Mvc\Controller;

class UserController extends Controller
{
    public function indexAction()
    {
        $this->persistent->name = "Michael";
    }

    public function welcomeAction()
    {
        echo "Welcome, ", $this->persistent->name;
    }
}
在控制器中使用服务(Using Services as Controllers)

服务可以是控制器,控制器类通常会从服务容器中请求。据于此, 任何一个用其名字注册的类都可以轻易地用一个控制器来替换:

<?php

// 将一个控制器作为服务进行注册
$di->set(
    "IndexController",
    function () {
        $component = new Component();

        return $component;
    }
);

// 将一个命名空间下的控制器作为服务进行注册
$di->set(
    "Backend\\Controllers\\IndexController",
    function () {
        $component = new Component();

        return $component;
    }
);
控制器中的事件(Events in Controllers)

控制器会自动作为 dispatcher 事件的侦听者,使用这些事件并实现这些方法后, 你便可以实现对应被执行的action的before/after钩子函数:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function beforeExecuteRoute($dispatcher)
    {
        // 这个方法会在每一个能找到的action前执行
        if ($dispatcher->getActionName() === "save") {
            $this->flash->error(
                "You don't have permission to save posts"
            );

            $this->dispatcher->forward(
                [
                    "controller" => "home",
                    "action"     => "index",
                ]
            );

            return false;
        }
    }

    public function afterExecuteRoute($dispatcher)
    {
        // 在找到的action后执行
    }
}

使用模型(Working with Models)

模型代表了应用程序中的信息(数据)和处理数据的规则。模型主要用于管理与相应数据库表进行交互的规则。 大多数情况中,在应用程序中,数据库中每个表将对应一个模型。 应用程序中的大部分业务逻辑都将集中在模型里。

Phalcon\Mvc\Model 是 Phalcon 应用程序中所有模型的基类。它保证了数据库的独立性,基本的 CURD 操作, 高级的查询功能,多表关联等功能。 Phalcon\Mvc\Model 不需要直接使用 SQL 语句,因为它的转换方法,会动态的调用相应的数据库引擎进行处理。

模型是数据库的高级抽象层。如果您想进行低层次的数据库操作,您可以查看 Phalcon\Db 组件文档。
创建模型

模型是一个继承自 Phalcon\Mvc\Model 的一个类。时它的类名必须符合驼峰命名法:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class RobotParts extends Model
{

}
如果使用 PHP 5.4/5.5 建议在模型中预先定义好所有的列,这样可以减少模型内存的开销以及内存分配。

默认情况下,模型 “Store\Toys\RobotParts” 对应的是数据库表 “robot_parts”, 如果想映射到其他数据库表,可以使用 setSource() 方法:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class RobotParts extends Model
{
    public function initialize()
    {
        $this->setSource("toys_robot_parts");
    }
}

模型 RobotParts 现在映射到了 “toys_robot_parts” 表。initialize() 方法可以帮助在模型中建立自定义行为,例如指定不同的数据库表。

initialize() 方法在请求期间仅会被调用一次,目的是为应用中所有该模型的实例进行初始化。如果需要为每一个实例在创建的时候单独进行初始化, 可以使用 onConstruct() 事件:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class RobotParts extends Model
{
    public function onConstruct()
    {
        // ...
    }
}
公共属性对比设置与取值 Setters/Getters(Public properties vs. Setters/Getters)

模型可以通过公共属性的方式实现,意味着模型的所有属性在实例化该模型的地方可以无限制的读取和更新。

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public $price;
}

通过使用 getters/setters 方法,可以控制哪些属性可以公开访问,并且对属性值执行不同的形式的转换,同时可以保存在模型中的数据添加相应的验证规则。

<?php

namespace Store\Toys;

use InvalidArgumentException;
use Phalcon\Mvc\Model;

class Robots extends Model
{
    protected $id;

    protected $name;

    protected $price;

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        // The name is too short?
        if (strlen($name) < 10) {
            throw new InvalidArgumentException(
                "The name is too short"
            );
        }

        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setPrice($price)
    {
        // Negative prices aren't allowed
        if ($price < 0) {
            throw new InvalidArgumentException(
                "Price can't be negative"
            );
        }

        $this->price = $price;
    }

    public function getPrice()
    {
        // Convert the value to double before be used
        return (double) $this->price;
    }
}

公共属性的方式可以在开发中降低复杂度。而 getters/setters 的实现方式可以显著的增强应用的可测试性、扩展性和可维护性。 开发人员可以自己决定哪一种策略更加适合自己开发的应用。ORM同时兼容这两种方法。

Underscores in property names can be problematic when using getters and setters.

If you use underscores in your property names, you must still use camel case in your getter/setter declarations for use with magic methods. (e.g. $model->getPropertyName instead of $model->getProperty_name, $model->findByPropertyName instead of $model->findByProperty_name, etc.). As much of the system expects camel case, and underscores are commonly removed, it is recommended to name your properties in the manner shown throughout the documentation. You can use a column map (as described above) to ensure proper mapping of your properties to their database counterparts.

理解记录对象(Understanding Records To Objects)

每个模型的实例对应一条数据表中的记录。可以方便的通过读取对象的属性来访问相应的数据。比如, 一个表 “robots” 有如下数据:

mysql> select * from robots;
+----+------------+------------+------+
| id | name       | type       | year |
+----+------------+------------+------+
|  1 | Robotina   | mechanical | 1972 |
|  2 | Astro Boy  | mechanical | 1952 |
|  3 | Terminator | cyborg     | 2029 |
+----+------------+------------+------+
3 rows in set (0.00 sec)

你可以通过主键找到某一条记录并且打印它的名称:

<?php

use Store\Toys\Robots;

// Find record with id = 3
$robot = Robots::findFirst(3);

// Prints "Terminator"
echo $robot->name;

一旦记录被加载到内存中之后,你可以修改它的数据并保存所做的修改:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(3);

$robot->name = "RoboCop";

$robot->save();

如上所示,不需要写任何SQL语句。Phalcon\Mvc\Model 为web应用提供了高层数据库抽象。

查找记录(Finding Records)

Phalcon\Mvc\Model 为数据查询提供了多种方法。下面的例子将演示如何从一个模型中查找一条或者多条记录:

<?php

use Store\Toys\Robots;

// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find("type = 'mechanical'");
echo "There are ", count($robots), "\n";

// Get and print virtual robots ordered by name
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
        "limit" => 100,
    ]
);
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}
如果需要通过外部数据(比如用户输入)或变量来查询记录,则必须要用`Binding Parameters`(绑定参数)的方式来防止SQL注入.

你可以使用 findFirst() 方法获取第一条符合查询条件的结果:

<?php

use Store\Toys\Robots;

// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";

// What's the first mechanical robot in robots table?
$robot = Robots::findFirst("type = 'mechanical'");
echo "The first mechanical robot name is ", $robot->name, "\n";

// Get first virtual robot ordered by name
$robot = Robots::findFirst(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);
echo "The first virtual robot name is ", $robot->name, "\n";

find()findFirst() 方法都接受关联数组作为查询条件:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(
    [
        "type = 'virtual'",
        "order" => "name DESC",
        "limit" => 30,
    ]
);

$robots = Robots::find(
    [
        "conditions" => "type = ?1",
        "bind"       => [
            1 => "virtual",
        ]
    ]
);

可用的查询选项如下:

参数 描述 举例
conditions 查询操作的搜索条件。用于提取只有那些满足指定条件的记录。默认情况下 Phalcon\Mvc\Model 假定第一个参数就是查询条件。 "conditions" => "name LIKE 'steve%'"
columns 只返回指定的字段,而不是模型所有的字段。 当用这个选项时,返回的是一个不完整的对象。 "columns" => "id, name"
bind 绑定与选项一起使用,通过替换占位符以及转义字段值从而增加安全性。 "bind" => ["status" => "A", "type" => "some-time"]
bindTypes 当绑定参数时,可以使用这个参数为绑定参数定义额外的类型限制从而更加增强安全性。 "bindTypes" => [Column::BIND_PARAM_STR, Column::BIND_PARAM_INT]
order 用于结果排序。使用一个或者多个字段,逗号分隔。 "order" => "name DESC, status"
limit 限制查询结果的数量在一定范围内。 "limit" => 10
offset Offset the results of the query by a certain amount "offset" => 5
group 从多条记录中获取数据并且根据一个或多个字段对结果进行分组。 "group" => "name, status"
for_update 通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置独占锁。 "for_update" => true
shared_lock 通过这个选项, Phalcon\Mvc\Model 读取最新的可用数据,并且为读到的每条记录设置共享锁。 "shared_lock" => true
cache 缓存结果集,减少了连续访问数据库。 "cache" => ["lifetime" => 3600, "key" => "my-find-key"]
hydration Sets the hydration strategy to represent each returned record in the result "hydration" => Resultset::HYDRATE_OBJECTS

如果你愿意,除了使用数组作为查询参数外,还可以通过一种面向对象的方式来创建查询:

<?php

use Store\Toys\Robots;

$robots = Robots::query()
    ->where("type = :type:")
    ->andWhere("year < 2000")
    ->bind(["type" => "mechanical"])
    ->order("name")
    ->execute();

静态方法 query() 返回一个对IDE自动完成友好的 Phalcon\Mvc\Model\Criteria 对象。

所有查询在内部都以 PHQL 查询的方式处理。PHQL是一个高层的、面向对象的类SQL语言。通过PHQL语言你可以使用更多的比如join其他模型、定义分组、添加聚集等特性。

最后,还有一个 findFirstBy<property-name>() 方法。这个方法扩展了前面提及的 findFirst() 方法。它允许您利用方法名中的属性名称,通过将要搜索的该字段的内容作为参数传给它,来快速从一个表执行检索操作。

还是用上面用过的 Robots 模型来举例说明:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public $price;
}

我们这里有3个属性:$id, $name$price。因此,我们以想要查询第一个名称为 ‘Terminator’ 的记录为例,可以这样写:

<?php

use Store\Toys\Robots;

$name = "Terminator";

$robot = Robots::findFirstByName($name);

if ($robot) {
    echo "The first robot with the name " . $name . " cost " . $robot->price . ".";
} else {
    echo "There were no robots found in our table with the name " . $name . ".";
}

请注意我们在方法调用中用的是 ‘Name’,并向它传递了变量 $name$name 的值就是我们想要找的记录的名称。另外注意,当我们的查询找到了符合的记录后,这个记录的其他属性也都是可用的。

模型结果集(Model Resultsets)

findFirst() 方法直接返回一个被调用对象的实例(如果有结果返回的话),而 find() 方法返回一个 Phalcon\Mvc\Model\Resultset\Simple 对象。这个对象也封装进了所有结果集的功能,比如遍历、查找特定的记录、统计等等。

这些对象比一般数组功能更强大。最大的特点是 Phalcon\Mvc\Model\Resultset 每时每刻只有一个结果在内存中。这对操作大数据量时的内存管理相当有帮助。

<?php

use Store\Toys\Robots;

// Get all robots
$robots = Robots::find();

// Traversing with a foreach
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Traversing with a while
$robots->rewind();

while ($robots->valid()) {
    $robot = $robots->current();

    echo $robot->name, "\n";

    $robots->next();
}

// Count the resultset
echo count($robots);

// Alternative way to count the resultset
echo $robots->count();

// Move the internal cursor to the third robot
$robots->seek(2);

$robot = $robots->current();

// Access a robot by its position in the resultset
$robot = $robots[5];

// Check if there is a record in certain position
if (isset($robots[3])) {
   $robot = $robots[3];
}

// Get the first record in the resultset
$robot = $robots->getFirst();

// Get the last record
$robot = $robots->getLast();

Phalcon 的结果集模拟了可滚动的游标,你可以通过位置,或者内部指针去访问任何一条特定的记录。注意有一些数据库系统不支持滚动游标,这就使得查询会被重复执行, 以便回放光标到最开始的位置,然后获得相应的记录。类似地,如果多次遍历结果集,那么必须执行相同的查询次数。

将大数据量的查询结果存储在内存会消耗很多资源,正因为如此,分成每32行一块从数据库中获得结果集,以减少重复执行查询请求的次数,在一些情况下也节省内存。

注意结果集可以序列化后保存在一个后端缓存里面。 Phalcon\Cache 可以用来实现这个。但是,序列化数据会导致 Phalcon\Mvc\Model 将从数据库检索到的所有数据以一个数组的方式保存,因此在这样执行的地方会消耗更多的内存。

<?php

// Query all records from model parts
$parts = Parts::find();

// Store the resultset into a file
file_put_contents(
    "cache.txt",
    serialize($parts)
);

// Get parts from file
$parts = unserialize(
    file_get_contents("cache.txt")
);

// Traverse the parts
foreach ($parts as $part) {
    echo $part->id;
}
过滤结果集(Filtering Resultsets)

过滤数据最有效的方法是设置一些查询条件,数据库会利用表的索引快速返回数据。Phalcon 额外的允许你通过任何数据库不支持的方式过滤数据。

<?php

$customers = Customers::find();

$customers = $customers->filter(
    function ($customer) {
        // Return only customers with a valid e-mail
        if (filter_var($customer->email, FILTER_VALIDATE_EMAIL)) {
            return $customer;
        }
    }
);
绑定参数(Binding Parameters)

Phalcon\Mvc\Model 中也支持绑定参数。即使使用绑定参数对性能有一点很小的影响,还是强烈建议您使用这种方法,以消除代码受SQL注入攻击的可能性。 绑定参数支持字符串和整数占位符。实现方法如下:

<?php

use Store\Toys\Robots;

// Query robots binding parameters with string placeholders
// Parameters whose keys are the same as placeholders
$robots = Robots::find(
    [
        "name = :name: AND type = :type:",
        "bind" => [
            "name" => "Robotina",
            "type" => "maid",
        ],
    ]
);

// Query robots binding parameters with integer placeholders
$robots = Robots::find(
    [
        "name = ?1 AND type = ?2",
        "bind" => [
            1 => "Robotina",
            2 => "maid",
        ],
    ]
);

// Query robots binding parameters with both string and integer placeholders
// Parameters whose keys are the same as placeholders
$robots = Robots::find(
    [
        "name = :name: AND type = ?1",
        "bind" => [
            "name" => "Robotina",
            1      => "maid",
        ],
    ]
);

如果是数字占位符,则必须把它们定义成整型(如1或者2)。若是定义为字符串型(如”1”或者”2”),则这个占位符不会被替换。

使用PDO_的方式会自动转义字符串。它依赖于字符集编码,因此建议在连接参数或者数据库配置中设置正确的字符集编码。 若是设置错误的字符集编码,在存储数据或检索数据时,可能会出现乱码。

另外你可以设置参数的“bindTypes”,这允许你根据数据类型来定义参数应该如何绑定:

<?php

use Phalcon\Db\Column;
use Store\Toys\Robots;

// Bind parameters
$parameters = [
    "name" => "Robotina",
    "year" => 2008,
];

// Casting Types
$types = [
    "name" => Column::BIND_PARAM_STR,
    "year" => Column::BIND_PARAM_INT,
];

// Query robots binding parameters with string placeholders
$robots = Robots::find(
    [
        "name = :name: AND year = :year:",
        "bind"      => $parameters,
        "bindTypes" => $types,
    ]
);
默认的参数绑定类型是 Phalcon\Db\Column::BIND_PARAM_STR , 若所有字段都是string类型,则不用特意去设置参数的“bindTypes”.

如果你的绑定参数是array数组,那么数组索引必须从数字0开始:

<?php

use Store\Toys\Robots;

$array = ["a","b","c"]; // $array: [[0] => "a", [1] => "b", [2] => "c"]

unset($array[1]); // $array: [[0] => "a", [2] => "c"]

// Now we have to renumber the keys
$array = array_values($array); // $array: [[0] => "a", [1] => "c"]

$robots = Robots::find(
    [
        'letter IN ({letter:array})',
        'bind' => [
            'letter' => $array
        ]
    ]
);
参数绑定的方式适用于所有与查询相关的方法,如 find() , findFirst() 等等, 同时也适用于与计算相关的方法,如 count(), sum(), average() 等等.

若使用如下方式,phalcon也会自动为你进行参数绑定:

<?php

use Store\Toys\Robots;

// Explicit query using bound parameters
$robots = Robots::find(
    [
        "name = ?0",
        "bind" => [
            "Ultron",
        ],
    ]
);

// Implicit query using bound parameters(隐式的参数绑定)
$robots = Robots::findByName("Ultron");
获取记录的初始化以及准备(Initializing/Preparing fetched records)

有时从数据库中获取了一条记录之后,在被应用程序使用之前,需要对数据进行初始化。 你可以在模型中实现”afterFetch”方法,在模型实例化之后会执行这个方法,并将数据分配给它:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public $status;

    public function beforeSave()
    {
        // Convert the array into a string
        $this->status = join(",", $this->status);
    }

    public function afterFetch()
    {
        // Convert the string to an array
        $this->status = explode(",", $this->status);
    }

    public function afterSave()
    {
        // Convert the string to an array
        $this->status = explode(",", $this->status);
    }
}

如果使用getters/setters方法代替公共属性的取/赋值,你能在它被调用时,对成员属性进行初始化:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public $status;

    public function getStatus()
    {
        return explode(",", $this->status);
    }
}
生成运算(Generating Calculations)

Calculations (or aggregations) are helpers for commonly used functions of database systems such as COUNT, SUM, MAX, MIN or AVG. Phalcon\Mvc\Model allows to use these functions directly from the exposed methods.

Count examples:

<?php

// How many employees are?
$rowcount = Employees::count();

// How many different areas are assigned to employees?
$rowcount = Employees::count(
    [
        "distinct" => "area",
    ]
);

// How many employees are in the Testing area?
$rowcount = Employees::count(
    "area = 'Testing'"
);

// Count employees grouping results by their area
$group = Employees::count(
    [
        "group" => "area",
    ]
);
foreach ($group as $row) {
   echo "There are ", $row->rowcount, " in ", $row->area;
}

// Count employees grouping by their area and ordering the result by count
$group = Employees::count(
    [
        "group" => "area",
        "order" => "rowcount",
    ]
);

// Avoid SQL injections using bound parameters
$group = Employees::count(
    [
        "type > ?0",
        "bind" => [
            $type
        ],
    ]
);

Sum examples:

<?php

// How much are the salaries of all employees?
$total = Employees::sum(
    [
        "column" => "salary",
    ]
);

// How much are the salaries of all employees in the Sales area?
$total = Employees::sum(
    [
        "column"     => "salary",
        "conditions" => "area = 'Sales'",
    ]
);

// Generate a grouping of the salaries of each area
$group = Employees::sum(
    [
        "column" => "salary",
        "group"  => "area",
    ]
);
foreach ($group as $row) {
   echo "The sum of salaries of the ", $row->area, " is ", $row->sumatory;
}

// Generate a grouping of the salaries of each area ordering
// salaries from higher to lower
$group = Employees::sum(
    [
        "column" => "salary",
        "group"  => "area",
        "order"  => "sumatory DESC",
    ]
);

// Avoid SQL injections using bound parameters
$group = Employees::sum(
    [
        "conditions" => "area > ?0",
        "bind"       => [
            $area
        ],
    ]
);

Average examples:

<?php

// What is the average salary for all employees?
$average = Employees::average(
    [
        "column" => "salary",
    ]
);

// What is the average salary for the Sales's area employees?
$average = Employees::average(
    [
        "column"     => "salary",
        "conditions" => "area = 'Sales'",
    ]
);

// Avoid SQL injections using bound parameters
$average = Employees::average(
    [
        "column"     => "age",
        "conditions" => "area > ?0",
        "bind"       => [
            $area
        ],
    ]
);

Max/Min examples:

<?php

// What is the oldest age of all employees?
$age = Employees::maximum(
    [
        "column" => "age",
    ]
);

// What is the oldest of employees from the Sales area?
$age = Employees::maximum(
    [
        "column"     => "age",
        "conditions" => "area = 'Sales'",
    ]
);

// What is the lowest salary of all employees?
$salary = Employees::minimum(
    [
        "column" => "salary",
    ]
);
创建与更新记录(Creating/Updating Records)

The Phalcon\Mvc\Model::save() method allows you to create/update records according to whether they already exist in the table associated with a model. The save method is called internally by the create and update methods of Phalcon\Mvc\Model. For this to work as expected it is necessary to have properly defined a primary key in the entity to determine whether a record should be updated or created.

Also the method executes associated validators, virtual foreign keys and events that are defined in the model:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

if ($robot->save() === false) {
    echo "Umh, We can't store robots right now: \n";

    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

An array could be passed to “save” to avoid assign every column manually. Phalcon\Mvc\Model will check if there are setters implemented for the columns passed in the array giving priority to them instead of assign directly the values of the attributes:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->save(
    [
        "type" => "mechanical",
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

Values assigned directly or via the array of attributes are escaped/sanitized according to the related attribute data type. So you can pass an insecure array without worrying about possible SQL injections:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->save($_POST);
Without precautions mass assignment could allow attackers to set any database column’s value. Only use this feature if you want to permit a user to insert/update every column in the model, even if those fields are not in the submitted form.

You can set an additional parameter in ‘save’ to set a whitelist of fields that only must taken into account when doing the mass assignment:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->save(
    $_POST,
    [
        "name",
        "type",
    ]
);
创建与更新结果判断(Create/Update with Confidence)

When an application has a lot of competition, we could be expecting create a record but it is actually updated. This could happen if we use Phalcon\Mvc\Model::save() to persist the records in the database. If we want to be absolutely sure that a record is created or updated, we can change the save() call with create() or update():

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

// This record only must be created
if ($robot->create() === false) {
    echo "Umh, We can't store robots right now: \n";

    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was created successfully!";
}

These methods “create” and “update” also accept an array of values as parameter.

删除记录(Deleting Records)

The Phalcon\Mvc\Model::delete() method allows to delete a record. You can use it as follows:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(11);

if ($robot !== false) {
    if ($robot->delete() === false) {
        echo "Sorry, we can't delete the robot right now: \n";

        $messages = $robot->getMessages();

        foreach ($messages as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

You can also delete many records by traversing a resultset with a foreach:

<?php

use Store\Toys\Robots;

$robots = Robots::find(
    "type = 'mechanical'"
);

foreach ($robots as $robot) {
    if ($robot->delete() === false) {
        echo "Sorry, we can't delete the robot right now: \n";

        $messages = $robot->getMessages();

        foreach ($messages as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

The following events are available to define custom business rules that can be executed when a delete operation is performed:

Operation Name Can stop operation? Explanation
Deleting beforeDelete YES Runs before the delete operation is made
Deleting afterDelete NO Runs after the delete operation was made

With the above events can also define business rules in the models:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function beforeDelete()
    {
        if ($this->status === "A") {
            echo "The robot is active, it can't be deleted";

            return false;
        }

        return true;
    }
}

Model Relationships

模型关系(Relationships between Models)

有四种关系类型:1对1,1对多,多对1,多对多。关系可以是单向或者双向的,每个关系可以是简单的(一个1对1的模型)也可以是复杂的(1组模型)。 The model manager manages foreign key constraints for these relationships, the definition of these helps referential integrity as well as easy and fast access of related records to a model. Through the implementation of relations, it is easy to access data in related models from each record in a uniform way.

单向关系(Unidirectional relationships)

Unidirectional relations are those that are generated in relation to one another but not vice versa.

双向关系(Bidirectional relations)

The bidirectional relations build relationships in both models and each model defines the inverse relationship of the other.

定义关系(Defining relationships)

In Phalcon, relationships must be defined in the initialize() method of a model. The methods belongsTo(), hasOne(), hasMany() and hasManyToMany() define the relationship between one or more fields from the current model to fields in another model. Each of these methods requires 3 parameters: local fields, referenced model, referenced fields.

Method Description
hasMany Defines a 1-n relationship
hasOne Defines a 1-1 relationship
belongsTo Defines a n-1 relationship
hasManyToMany Defines a n-n relationship

The following schema shows 3 tables whose relations will serve us as an example regarding relationships:

CREATE TABLE `robots` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(70) NOT NULL,
    `type` varchar(32) NOT NULL,
    `year` int(11) NOT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE `robots_parts` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `robots_id` int(10) NOT NULL,
    `parts_id` int(10) NOT NULL,
    `created_at` DATE NOT NULL,
    PRIMARY KEY (`id`),
    KEY `robots_id` (`robots_id`),
    KEY `parts_id` (`parts_id`)
);

CREATE TABLE `parts` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `name` varchar(70) NOT NULL,
    PRIMARY KEY (`id`)
);
  • The model “Robots” has many “RobotsParts”.
  • The model “Parts” has many “RobotsParts”.
  • The model “RobotsParts” belongs to both “Robots” and “Parts” models as a many-to-one relation.
  • The model “Robots” has a relation many-to-many to “Parts” through “RobotsParts”.

Check the EER diagram to understand better the relations:

_images/eer-1.png

The models with their relations could be implemented as follows:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id",
            "RobotsParts",
            "robots_id"
        );
    }
}
<?php

use Phalcon\Mvc\Model;

class Parts extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id",
            "RobotsParts",
            "parts_id"
        );
    }
}
<?php

use Phalcon\Mvc\Model;

class RobotsParts extends Model
{
    public $id;

    public $robots_id;

    public $parts_id;

    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            "Store\\Toys\\Robots",
            "id"
        );

        $this->belongsTo(
            "parts_id",
            "Parts",
            "id"
        );
    }
}

The first parameter indicates the field of the local model used in the relationship; the second indicates the name of the referenced model and the third the field name in the referenced model. You could also use arrays to define multiple fields in the relationship.

Many to many relationships require 3 models and define the attributes involved in the relationship:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasManyToMany(
            "id",
            "RobotsParts",
            "robots_id", "parts_id",
            "Parts",
            "id"
        );
    }
}
使用关系(Taking advantage of relationships)

When explicitly defining the relationships between models, it is easy to find related records for a particular record.

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(2);

foreach ($robot->robotsParts as $robotPart) {
    echo $robotPart->parts->name, "\n";
}

Phalcon uses the magic methods __set/__get/__call to store or retrieve related data using relationships.

By accessing an attribute with the same name as the relationship will retrieve all its related record(s).

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst();

// All the related records in RobotsParts
$robotsParts = $robot->robotsParts;

Also, you can use a magic getter:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst();

// All the related records in RobotsParts
$robotsParts = $robot->getRobotsParts();

// Passing parameters
$robotsParts = $robot->getRobotsParts(
    [
        "limit" => 5,
    ]
);

If the called method has a “get” prefix Phalcon\Mvc\Model will return a findFirst()/find() result. The following example compares retrieving related results with using magic methods and without:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(2);

// Robots model has a 1-n (hasMany)
// relationship to RobotsParts then
$robotsParts = $robot->robotsParts;

// Only parts that match conditions
$robotsParts = $robot->getRobotsParts(
    [
        "created_at = :date:",
        "bind" => [
            "date" => "2015-03-15"
        ]
    ]
);

$robotPart = RobotsParts::findFirst(1);

// RobotsParts model has a n-1 (belongsTo)
// relationship to RobotsParts then
$robot = $robotPart->robots;

Getting related records manually:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(2);

// Robots model has a 1-n (hasMany)
// relationship to RobotsParts, then
$robotsParts = RobotsParts::find(
    [
        "robots_id = :id:",
        "bind" => [
            "id" => $robot->id,
        ]
    ]
);

// Only parts that match conditions
$robotsParts = RobotsParts::find(
    [
        "robots_id = :id: AND created_at = :date:",
        "bind" => [
            "id"   => $robot->id,
            "date" => "2015-03-15",
        ]
    ]
);

$robotPart = RobotsParts::findFirst(1);

// RobotsParts model has a n-1 (belongsTo)
// relationship to RobotsParts then
$robot = Robots::findFirst(
    [
        "id = :id:",
        "bind" => [
            "id" => $robotPart->robots_id,
        ]
    ]
);

The prefix “get” is used to find()/findFirst() related records. Depending on the type of relation it will use find() or findFirst():

Type Description Implicit Method
Belongs-To Returns a model instance of the related record directly findFirst
Has-One Returns a model instance of the related record directly findFirst
Has-Many Returns a collection of model instances of the referenced model find
Has-Many-to-Many Returns a collection of model instances of the referenced model, it implicitly does ‘inner joins’ with the involved models (complex query)

You can also use the “count” prefix to return an integer denoting the count of the related records:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst(2);

echo "The robot has ", $robot->countRobotsParts(), " parts\n";
定义关系(Aliasing Relationships)

To explain better how aliases work, let’s check the following example:

The “robots_similar” table has the function to define what robots are similar to others:

mysql> desc robots_similar;
+-------------------+------------------+------+-----+---------+----------------+
| Field             | Type             | Null | Key | Default | Extra          |
+-------------------+------------------+------+-----+---------+----------------+
| id                | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| robots_id         | int(10) unsigned | NO   | MUL | NULL    |                |
| similar_robots_id | int(10) unsigned | NO   |     | NULL    |                |
+-------------------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

Both “robots_id” and “similar_robots_id” have a relation to the model Robots:

_images/eer-2.png

A model that maps this table and its relationships is the following:

<?php

class RobotsSimilar extends Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            "Store\\Toys\\Robots",
            "id"
        );

        $this->belongsTo(
            "similar_robots_id",
            "Store\\Toys\\Robots",
            "id"
        );
    }
}

Since both relations point to the same model (Robots), obtain the records related to the relationship could not be clear:

<?php

$robotsSimilar = RobotsSimilar::findFirst();

// Returns the related record based on the column (robots_id)
// Also as is a belongsTo it's only returning one record
// but the name 'getRobots' seems to imply that return more than one
$robot = $robotsSimilar->getRobots();

// but, how to get the related record based on the column (similar_robots_id)
// if both relationships have the same name?

The aliases allow us to rename both relationships to solve these problems:

<?php

use Phalcon\Mvc\Model;

class RobotsSimilar extends Model
{
    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            "Store\\Toys\\Robots",
            "id",
            [
                "alias" => "Robot",
            ]
        );

        $this->belongsTo(
            "similar_robots_id",
            "Store\\Toys\\Robots",
            "id",
            [
                "alias" => "SimilarRobot",
            ]
        );
    }
}

With the aliasing we can get the related records easily:

<?php

$robotsSimilar = RobotsSimilar::findFirst();

// Returns the related record based on the column (robots_id)
$robot = $robotsSimilar->getRobot();
$robot = $robotsSimilar->robot;

// Returns the related record based on the column (similar_robots_id)
$similarRobot = $robotsSimilar->getSimilarRobot();
$similarRobot = $robotsSimilar->similarRobot;
魔术方法 Getters 对比显示方法(Magic Getters vs. Explicit methods)

Most IDEs and editors with auto-completion capabilities can not infer the correct types when using magic getters, instead of use the magic getters you can optionally define those methods explicitly with the corresponding docblocks helping the IDE to produce a better auto-completion:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id",
            "RobotsParts",
            "robots_id"
        );
    }

    /**
     * Return the related "robots parts"
     *
     * @return \RobotsParts[]
     */
    public function getRobotsParts($parameters = null)
    {
        return $this->getRelated("RobotsParts", $parameters);
    }
}
虚拟外键(Virtual Foreign Keys)

By default, relationships do not act like database foreign keys, that is, if you try to insert/update a value without having a valid value in the referenced model, Phalcon will not produce a validation message. You can modify this behavior by adding a fourth parameter when defining a relationship.

The RobotsPart model can be changed to demonstrate this feature:

<?php

use Phalcon\Mvc\Model;

class RobotsParts extends Model
{
    public $id;

    public $robots_id;

    public $parts_id;

    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            "Store\\Toys\\Robots",
            "id",
            [
                "foreignKey" => true
            ]
        );

        $this->belongsTo(
            "parts_id",
            "Parts",
            "id",
            [
                "foreignKey" => [
                    "message" => "The part_id does not exist on the Parts model"
                ]
            ]
        );
    }
}

If you alter a belongsTo() relationship to act as foreign key, it will validate that the values inserted/updated on those fields have a valid value on the referenced model. Similarly, if a hasMany()/hasOne() is altered it will validate that the records cannot be deleted if that record is used on a referenced model.

<?php

use Phalcon\Mvc\Model;

class Parts extends Model
{
    public function initialize()
    {
        $this->hasMany(
            "id",
            "RobotsParts",
            "parts_id",
            [
                "foreignKey" => [
                    "message" => "The part cannot be deleted because other robots are using it",
                ]
            ]
        );
    }
}

A virtual foreign key can be set up to allow null values as follows:

<?php

use Phalcon\Mvc\Model;

class RobotsParts extends Model
{
    public $id;

    public $robots_id;

    public $parts_id;

    public function initialize()
    {
        $this->belongsTo(
            "parts_id",
            "Parts",
            "id",
            [
                "foreignKey" => [
                    "allowNulls" => true,
                    "message"    => "The part_id does not exist on the Parts model",
                ]
            ]
        );
    }
}
级联与限制动作(Cascade/Restrict actions)

Relationships that act as virtual foreign keys by default restrict the creation/update/deletion of records to maintain the integrity of data:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Relation;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            "id",
            "Parts",
            "robots_id",
            [
                "foreignKey" => [
                    "action" => Relation::ACTION_CASCADE,
                ]
            ]
        );
    }
}

The above code set up to delete all the referenced records (parts) if the master record (robot) is deleted.

在结果集中操作(Operations over Resultsets)

If a resultset is composed of complete objects, the resultset is in the ability to perform operations on the records obtained in a simple manner:

Model Events

事件与事件管理器(Events and Events Manager)

Models allow you to implement events that will be thrown when performing an insert/update/delete. They help define business rules for a certain model. The following are the events supported by Phalcon\Mvc\Model and their order of execution:

Operation Name Can stop operation? Explanation
Inserting/Updating beforeValidation YES Is executed before the fields are validated for not nulls/empty strings or foreign keys
Inserting beforeValidationOnCreate YES Is executed before the fields are validated for not nulls/empty strings or foreign keys when an insertion operation is being made
Updating beforeValidationOnUpdate YES Is executed before the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made
Inserting/Updating onValidationFails YES (already stopped) Is executed after an integrity validator fails
Inserting afterValidationOnCreate YES Is executed after the fields are validated for not nulls/empty strings or foreign keys when an insertion operation is being made
Updating afterValidationOnUpdate YES Is executed after the fields are validated for not nulls/empty strings or foreign keys when an updating operation is being made
Inserting/Updating afterValidation YES Is executed after the fields are validated for not nulls/empty strings or foreign keys
Inserting/Updating beforeSave YES Runs before the required operation over the database system
Updating beforeUpdate YES Runs before the required operation over the database system only when an updating operation is being made
Inserting beforeCreate YES Runs before the required operation over the database system only when an inserting operation is being made
Updating afterUpdate NO Runs after the required operation over the database system only when an updating operation is being made
Inserting afterCreate NO Runs after the required operation over the database system only when an inserting operation is being made
Inserting/Updating afterSave NO Runs after the required operation over the database system
模型中自定义事件(Implementing Events in the Model’s class)

The easier way to make a model react to events is implement a method with the same name of the event in the model’s class:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function beforeValidationOnCreate()
    {
        echo "This is executed before creating a Robot!";
    }
}

Events can be useful to assign values before performing an operation, for example:

<?php

use Phalcon\Mvc\Model;

class Products extends Model
{
    public function beforeCreate()
    {
        // Set the creation date
        $this->created_at = date("Y-m-d H:i:s");
    }

    public function beforeUpdate()
    {
        // Set the modification date
        $this->modified_in = date("Y-m-d H:i:s");
    }
}
使用自定义事件管理器(Using a custom Events Manager)

Additionally, this component is integrated with Phalcon\Events\Manager, this means we can create listeners that run when an event is triggered.

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

class Robots extends Model
{
    public function initialize()
    {
        $eventsManager = new EventsManager();

        // Attach an anonymous function as a listener for "model" events
        $eventsManager->attach(
            "model:beforeSave",
            function (Event $event, $robot) {
                if ($robot->name === "Scooby Doo") {
                    echo "Scooby Doo isn't a robot!";

                    return false;
                }

                return true;
            }
        );

        // Attach the events manager to the event
        $this->setEventsManager($eventsManager);
    }
}

In the example given above, the Events Manager only acts as a bridge between an object and a listener (the anonymous function). Events will be fired to the listener when ‘robots’ are saved:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->name = "Scooby Doo";
$robot->year = 1969;

$robot->save();

If we want all objects created in our application use the same EventsManager, then we need to assign it to the Models Manager:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

// Registering the modelsManager service
$di->setShared(
    "modelsManager",
    function () {
        $eventsManager = new EventsManager();

        // Attach an anonymous function as a listener for "model" events
        $eventsManager->attach(
            "model:beforeSave",
            function (Event $event, $model) {
                // Catch events produced by the Robots model
                if (get_class($model) === "Store\\Toys\\Robots") {
                    if ($model->name === "Scooby Doo") {
                        echo "Scooby Doo isn't a robot!";

                        return false;
                    }
                }

                return true;
            }
        );

        // Setting a default EventsManager
        $modelsManager = new ModelsManager();

        $modelsManager->setEventsManager($eventsManager);

        return $modelsManager;
    }
);

If a listener returns false that will stop the operation that is executing currently.

记录底层 SQL 语句(Logging Low-Level SQL Statements)

When using high-level abstraction components such as Phalcon\Mvc\Model to access a database, it is difficult to understand which statements are finally sent to the database system. Phalcon\Mvc\Model is supported internally by Phalcon\Db. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer, thus allowing us to log SQL statements as they happen.

<?php

use Phalcon\Logger;
use Phalcon\Events\Manager;
use Phalcon\Logger\Adapter\File as FileLogger;
use Phalcon\Db\Adapter\Pdo\Mysql as Connection;

$di->set(
    "db",
    function () {
        $eventsManager = new EventsManager();

        $logger = new FileLogger("app/logs/debug.log");

        // Listen all the database events
        $eventsManager->attach(
            "db:beforeQuery",
            function ($event, $connection) use ($logger) {
                $logger->log(
                    $connection->getSQLStatement(),
                    Logger::INFO
                );
            }
        );

        $connection = new Connection(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );

        // Assign the eventsManager to the db adapter instance
        $connection->setEventsManager($eventsManager);

        return $connection;
    }
);

As models access the default database connection, all SQL statements that are sent to the database system will be logged in the file:

<?php

use Store\Toys\Robots;

$robot = new Robots();

$robot->name       = "Robby the Robot";
$robot->created_at = "1956-07-21";

if ($robot->save() === false) {
    echo "Cannot save robot";
}

As above, the file app/logs/db.log will contain something like this:

[Mon, 30 Apr 12 13:47:18 -0500][DEBUG][Resource Id #77] INSERT INTO robots
(name, created_at) VALUES ('Robby the Robot', '1956-07-21')
分析 SQL 语句(Profiling SQL Statements)

Thanks to Phalcon\Db, the underlying component of Phalcon\Mvc\Model, it’s possible to profile the SQL statements generated by the ORM in order to analyze the performance of database operations. With this you can diagnose performance problems and to discover bottlenecks.

<?php

use Phalcon\Db\Profiler as ProfilerDb;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;

$di->set(
    "profiler",
    function () {
        return new ProfilerDb();
    },
    true
);

$di->set(
    "db",
    function () use ($di) {
        $eventsManager = new EventsManager();

        // Get a shared instance of the DbProfiler
        $profiler = $di->getProfiler();

        // Listen all the database events
        $eventsManager->attach(
            "db",
            function ($event, $connection) use ($profiler) {
                if ($event->getType() === "beforeQuery") {
                    $profiler->startProfile(
                        $connection->getSQLStatement()
                    );
                }

                if ($event->getType() === "afterQuery") {
                    $profiler->stopProfile();
                }
            }
        );

        $connection = new MysqlPdo(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );

        // Assign the eventsManager to the db adapter instance
        $connection->setEventsManager($eventsManager);

        return $connection;
    }
);

Profiling some queries:

<?php

use Store\Toys\Robots;

// Send some SQL statements to the database
Robots::find();

Robots::find(
    [
        "order" => "name",
    ]
);

Robots::find(
    [
        "limit" => 30,
    ]
);

// Get the generated profiles from the profiler
$profiles = $di->get("profiler")->getProfiles();

foreach ($profiles as $profile) {
   echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
   echo "Start Time: ", $profile->getInitialTime(), "\n";
   echo "Final Time: ", $profile->getFinalTime(), "\n";
   echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
}

Each generated profile contains the duration in milliseconds that each instruction takes to complete as well as the generated SQL statement.

Model Behaviors

Behaviors are shared conducts that several models may adopt in order to re-use code, the ORM provides an API to implement behaviors in your models. Also, you can use the events and callbacks as seen before as an alternative to implement Behaviors with more freedom.

A behavior must be added in the model initializer, a model can have zero or more behaviors:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;

class Users extends Model
{
    public $id;

    public $name;

    public $created_at;

    public function initialize()
    {
        $this->addBehavior(
            new Timestampable(
                [
                    "beforeCreate" => [
                        "field"  => "created_at",
                        "format" => "Y-m-d",
                    ]
                ]
            )
        );
    }
}

The following built-in behaviors are provided by the framework:

Name Description
Timestampable Allows to automatically update a model’s attribute saving the datetime when a record is created or updated
SoftDelete Instead of permanently delete a record it marks the record as deleted changing the value of a flag column
生成时间戳(Timestampable)

This behavior receives an array of options, the first level key must be an event name indicating when the column must be assigned:

<?php

use Phalcon\Mvc\Model\Behavior\Timestampable;

public function initialize()
{
    $this->addBehavior(
        new Timestampable(
            [
                "beforeCreate" => [
                    "field"  => "created_at",
                    "format" => "Y-m-d",
                ]
            ]
        )
    );
}

Each event can have its own options, ‘field’ is the name of the column that must be updated, if ‘format’ is a string it will be used as format of the PHP’s function date, format can also be an anonymous function providing you the free to generate any kind timestamp:

<?php

use DateTime;
use DateTimeZone;
use Phalcon\Mvc\Model\Behavior\Timestampable;

public function initialize()
{
    $this->addBehavior(
        new Timestampable(
            [
                "beforeCreate" => [
                    "field"  => "created_at",
                    "format" => function () {
                        $datetime = new Datetime(
                            new DateTimeZone("Europe/Stockholm")
                        );

                        return $datetime->format("Y-m-d H:i:sP");
                    }
                ]
            ]
        )
    );
}

If the option ‘format’ is omitted a timestamp using the PHP’s function time, will be used.

软删除(SoftDelete)

This behavior can be used in the following way:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;

class Users extends Model
{
    const DELETED = "D";

    const NOT_DELETED = "N";



    public $id;

    public $name;

    public $status;



    public function initialize()
    {
        $this->addBehavior(
            new SoftDelete(
                [
                    "field" => "status",
                    "value" => Users::DELETED,
                ]
            )
        );
    }
}

This behavior accepts two options: ‘field’ and ‘value’, ‘field’ determines what field must be updated and ‘value’ the value to be deleted. Let’s pretend the table ‘users’ has the following data:

mysql> select * from users;
+----+---------+--------+
| id | name    | status |
+----+---------+--------+
|  1 | Lana    | N      |
|  2 | Brandon | N      |
+----+---------+--------+
2 rows in set (0.00 sec)

If we delete any of the two records the status will be updated instead of delete the record:

<?php

Users::findFirst(2)->delete();

The operation will result in the following data in the table:

mysql> select * from users;
+----+---------+--------+
| id | name    | status |
+----+---------+--------+
|  1 | Lana    | N      |
|  2 | Brandon | D      |
+----+---------+--------+
2 rows in set (0.01 sec)

Note that you need to specify the deleted condition in your queries to effectively ignore them as deleted records, this behavior doesn’t support that.

创建行为(Creating your own behaviors)

The ORM provides an API to create your own behaviors. A behavior must be a class implementing the Phalcon\Mvc\Model\BehaviorInterface. Also, Phalcon\Mvc\Model\Behavior provides most of the methods needed to ease the implementation of behaviors.

The following behavior is an example, it implements the Blameable behavior which helps identify the user that is performed operations over a model:

<?php

use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;

class Blameable extends Behavior implements BehaviorInterface
{
    public function notify($eventType, $model)
    {
        switch ($eventType) {

            case "afterCreate":
            case "afterDelete":
            case "afterUpdate":

                $userName = // ... get the current user from session

                // Store in a log the username, event type and primary key
                file_put_contents(
                    "logs/blamable-log.txt",
                    $userName . " " . $eventType . " " . $model->id
                );

                break;

            default:
                /* ignore the rest of events */
        }
    }
}

The former is a very simple behavior, but it illustrates how to create a behavior, now let’s add this behavior to a model:

<?php

use Phalcon\Mvc\Model;

class Profiles extends Model
{
    public function initialize()
    {
        $this->addBehavior(
            new Blameable()
        );
    }
}

A behavior is also capable of intercepting missing methods on your models:

<?php

use Phalcon\Tag;
use Phalcon\Mvc\Model\Behavior;
use Phalcon\Mvc\Model\BehaviorInterface;

class Sluggable extends Behavior implements BehaviorInterface
{
    public function missingMethod($model, $method, $arguments = [])
    {
        // If the method is 'getSlug' convert the title
        if ($method === "getSlug") {
            return Tag::friendlyTitle($model->title);
        }
    }
}

Call that method on a model that implements Sluggable returns a SEO friendly title:

<?php

$title = $post->getSlug();
使用 Traits 实现行为(Using Traits as behaviors)

Starting from PHP 5.4 you can use Traits to re-use code in your classes, this is another way to implement custom behaviors. The following trait implements a simple version of the Timestampable behavior:

<?php

trait MyTimestampable
{
    public function beforeCreate()
    {
        $this->created_at = date("r");
    }

    public function beforeUpdate()
    {
        $this->updated_at = date("r");
    }
}

Then you can use it in your model as follows:

<?php

use Phalcon\Mvc\Model;

class Products extends Model
{
    use MyTimestampable;
}

模型元数据(Models Metadata)

To speed up development Phalcon\Mvc\Model helps you to query fields and constraints from tables related to models. To achieve this, Phalcon\Mvc\Model\MetaData is available to manage and cache table metadata.

Sometimes it is necessary to get those attributes when working with models. You can get a metadata instance as follows:

<?php

$robot = new Robots();

// Get Phalcon\Mvc\Model\Metadata instance
$metadata = $robot->getModelsMetaData();

// Get robots fields names
$attributes = $metadata->getAttributes($robot);
print_r($attributes);

// Get robots fields data types
$dataTypes = $metadata->getDataTypes($robot);
print_r($dataTypes);
缓存元数据(Caching Metadata)

Once the application is in a production stage, it is not necessary to query the metadata of the table from the database system each time you use the table. This could be done caching the metadata using any of the following adapters:

Adapter Description API
Memory This adapter is the default. The metadata is cached only during the request. When the request is completed, the metadata are released as part of the normal memory of the request. This adapter is perfect when the application is in development so as to refresh the metadata in each request containing the new and/or modified fields. Phalcon\Mvc\Model\MetaData\Memory
Session This adapter stores metadata in the $_SESSION superglobal. This adapter is recommended only when the application is actually using a small number of models. The metadata are refreshed every time a new session starts. This also requires the use of session_start() to start the session before using any models. Phalcon\Mvc\Model\MetaData\Session
Apc This adapter uses the Alternative PHP Cache (APC) to store the table metadata. You can specify the lifetime of the metadata with options. This is the most recommended way to store metadata when the application is in production stage. Phalcon\Mvc\Model\MetaData\Apc
XCache This adapter uses XCache to store the table metadata. You can specify the lifetime of the metadata with options. This is the most recommended way to store metadata when the application is in production stage. Phalcon\Mvc\Model\MetaData\Xcache
Files This adapter uses plain files to store metadata. By using this adapter the disk-reading is increased but the database access is reduced. Phalcon\Mvc\Model\MetaData\Files

As other ORM’s dependencies, the metadata manager is requested from the services container:

<?php

use Phalcon\Mvc\Model\MetaData\Apc as ApcMetaData;

$di["modelsMetadata"] = function () {
    // Create a metadata manager with APC
    $metadata = new ApcMetaData(
        [
            "lifetime" => 86400,
            "prefix"   => "my-prefix",
        ]
    );

    return $metadata;
};
元数据策略(Metadata Strategies)

As mentioned above the default strategy to obtain the model’s metadata is database introspection. In this strategy, the information schema is used to know the fields in a table, its primary key, nullable fields, data types, etc.

You can change the default metadata introspection in the following way:

<?php

use Phalcon\Mvc\Model\MetaData\Apc as ApcMetaData;

$di["modelsMetadata"] = function () {
    // Instantiate a metadata adapter
    $metadata = new ApcMetaData(
        [
            "lifetime" => 86400,
            "prefix"   => "my-prefix",
        ]
    );

    // Set a custom metadata introspection strategy
    $metadata->setStrategy(
        new MyIntrospectionStrategy()
    );

    return $metadata;
};
数据库内部策略(Database Introspection Strategy)

This strategy doesn’t require any customization and is implicitly used by all the metadata adapters.

注释策略(Annotations Strategy)

This strategy makes use of annotations to describe the columns in a model:

<?php

use Phalcon\Mvc\Model;

class Robots extends Model
{
    /**
     * @Primary
     * @Identity
     * @Column(type="integer", nullable=false)
     */
    public $id;

    /**
     * @Column(type="string", length=70, nullable=false)
     */
    public $name;

    /**
     * @Column(type="string", length=32, nullable=false)
     */
    public $type;

    /**
     * @Column(type="integer", nullable=false)
     */
    public $year;
}

Annotations must be placed in properties that are mapped to columns in the mapped source. Properties without the @Column annotation are handled as simple class attributes.

The following annotations are supported:

Name Description
Primary Mark the field as part of the table’s primary key
Identity The field is an auto_increment/serial column
Column This marks an attribute as a mapped column

The annotation @Column supports the following parameters:

Name Description
type The column’s type (string, integer, decimal, boolean)
length The column’s length if any
nullable Set whether the column accepts null values or not

The annotations strategy could be set up this way:

<?php

use Phalcon\Mvc\Model\MetaData\Apc as ApcMetaData;
use Phalcon\Mvc\Model\MetaData\Strategy\Annotations as StrategyAnnotations;

$di["modelsMetadata"] = function () {
    // Instantiate a metadata adapter
    $metadata = new ApcMetaData(
        [
            "lifetime" => 86400,
            "prefix"   => "my-prefix",
        ]
    );

    // Set a custom metadata database introspection
    $metadata->setStrategy(
        new StrategyAnnotations()
    );

    return $metadata;
};
自定义元数据(Manual Metadata)

Phalcon can obtain the metadata for each model automatically without the developer must set them manually using any of the introspection strategies presented above.

The developer also has the option of define the metadata manually. This strategy overrides any strategy set in the metadata manager. New columns added/modified/removed to/from the mapped table must be added/modified/removed also for everything to work properly.

The following example shows how to define the metadata manually:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Db\Column;
use Phalcon\Mvc\Model\MetaData;

class Robots extends Model
{
    public function metaData()
    {
        return array(
            // Every column in the mapped table
            MetaData::MODELS_ATTRIBUTES => [
                "id",
                "name",
                "type",
                "year",
            ],

            // Every column part of the primary key
            MetaData::MODELS_PRIMARY_KEY => [
                "id",
            ],

            // Every column that isn't part of the primary key
            MetaData::MODELS_NON_PRIMARY_KEY => [
                "name",
                "type",
                "year",
            ],

            // Every column that doesn't allows null values
            MetaData::MODELS_NOT_NULL => [
                "id",
                "name",
                "type",
            ],

            // Every column and their data types
            MetaData::MODELS_DATA_TYPES => [
                "id"   => Column::TYPE_INTEGER,
                "name" => Column::TYPE_VARCHAR,
                "type" => Column::TYPE_VARCHAR,
                "year" => Column::TYPE_INTEGER,
            ],

            // The columns that have numeric data types
            MetaData::MODELS_DATA_TYPES_NUMERIC => [
                "id"   => true,
                "year" => true,
            ],

            // The identity column, use boolean false if the model doesn't have
            // an identity column
            MetaData::MODELS_IDENTITY_COLUMN => "id",

            // How every column must be bound/casted
            MetaData::MODELS_DATA_TYPES_BIND => [
                "id"   => Column::BIND_PARAM_INT,
                "name" => Column::BIND_PARAM_STR,
                "type" => Column::BIND_PARAM_STR,
                "year" => Column::BIND_PARAM_INT,
            ],

            // Fields that must be ignored from INSERT SQL statements
            MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT => [
                "year" => true,
            ],

            // Fields that must be ignored from UPDATE SQL statements
            MetaData::MODELS_AUTOMATIC_DEFAULT_UPDATE => [
                "year" => true,
            ],

            // Default values for columns
            MetaData::MODELS_DEFAULT_VALUES => [
                "year" => "2015",
            ],

            // Fields that allow empty strings
            MetaData::MODELS_EMPTY_STRING_VALUES => [
                "name" => true,
            ],
        );
    }
}

事务管理(Model Transactions)

当一个进程执行多个数据库操作时,通常需要每一步都是成功完成以便保证数据完整性。事务可以确保在数据提交到数据库保存之前所有数据库操作都成功执行。

Phalcon中通过事务,可以在所有操作都成功执行之后提交到服务器,或者当有错误发生时回滚所有的操作。

自定义事务(Manual Transactions)

如果一个应用只用到了一个数据库连接并且这些事务都不太复杂,那么可以通过简单的将当前数据库连接设置成事务模式实现事务功能,根据操作的成功与否提交或者回滚:

<?php

use Phalcon\Mvc\Controller;

class RobotsController extends Controller
{
    public function saveAction()
    {
        // Start a transaction
        $this->db->begin();

        $robot = new Robots();

        $robot->name       = "WALL·E";
        $robot->created_at = date("Y-m-d");

        // The model failed to save, so rollback the transaction
        if ($robot->save() === false) {
            $this->db->rollback();
            return;
        }

        $robotPart = new RobotParts();

        $robotPart->robots_id = $robot->id;
        $robotPart->type      = "head";

        // The model failed to save, so rollback the transaction
        if ($robotPart->save() === false) {
            $this->db->rollback();

            return;
        }

        // Commit the transaction
        $this->db->commit();
    }
}
隐含的事务(Implicit Transactions)

也可以通过已有的关系来存储记录以及其相关记录,这种操作将隐式地创建一个事务来保证所有数据都能够正确地保存:

<?php

$robotPart = new RobotParts();

$robotPart->type = "head";



$robot = new Robots();

$robot->name       = "WALL·E";
$robot->created_at = date("Y-m-d");
$robot->robotPart  = $robotPart;

// Creates an implicit transaction to store both records
$robot->save();
单独的事务(Isolated Transactions)

单独事务在一个新的连接中执行所有的SQL,虚拟外键检查和业务规则与主数据库连接是相互独立的。 这种事务需要一个事务管理器来全局的管理每一个事务,保证他们在请求结束前能正确的回滚或者提交。

<?php

use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;

try {
    // Create a transaction manager
    $manager = new TxManager();

    // Request a transaction
    $transaction = $manager->get();

    $robot = new Robots();

    $robot->setTransaction($transaction);

    $robot->name       = "WALL·E";
    $robot->created_at = date("Y-m-d");

    if ($robot->save() === false) {
        $transaction->rollback(
            "Cannot save robot"
        );
    }

    $robotPart = new RobotParts();

    $robotPart->setTransaction($transaction);

    $robotPart->robots_id = $robot->id;
    $robotPart->type      = "head";

    if ($robotPart->save() === false) {
        $transaction->rollback(
            "Cannot save robot part"
        );
    }

    // Everything's gone fine, let's commit the transaction
    $transaction->commit();
} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

事务可以用以保证以一致性的方式删除多条记录:

<?php

use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;

try {
    // Create a transaction manager
    $manager = new TxManager();

    // Request a transaction
    $transaction = $manager->get();

    // Get the robots to be deleted
    $robots = Robots::find(
        "type = 'mechanical'"
    );

    foreach ($robots as $robot) {
        $robot->setTransaction($transaction);

        // Something's gone wrong, we should rollback the transaction
        if ($robot->delete() === false) {
            $messages = $robot->getMessages();

            foreach ($messages as $message) {
                $transaction->rollback(
                    $message->getMessage()
                );
            }
        }
    }

    // Everything's gone fine, let's commit the transaction
    $transaction->commit();

    echo "Robots were deleted successfully!";
} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

事务对象可以重用,不管事务对象是在什么地方获取的。只有当一个:code:`commit()`或者一个:code:`rollback()`执行时才会创建一个新的事务对象。可以通过服务容器在整个应用中来创建和管理全局事务管理器。

<?php

use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager

$di->setShared(
    "transactions",
    function () {
        return new TransactionManager();
    }
);

然后在控制器或者视图中访问:

<?php

use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function saveAction()
    {
        // Obtain the TransactionsManager from the services container
        $manager = $this->di->getTransactions();

        // Or
        $manager = $this->transactions;

        // Request a transaction
        $transaction = $manager->get();

        // ...
    }
}

当一个事务处于活动状态时,在整个应用中事务管理器将总是返回这个相同的事务。

Validating Models

验证数据完整性(Validating Data Integrity)

Phalcon\Mvc\Model provides several events to validate data and implement business rules. The special “validation” event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation.

The following example shows how to use it:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
use Phalcon\Validation\Validator\InclusionIn;

class Robots extends Model
{
    public function validation()
    {
        $validator = new Validation();

        $validator->add(
            "type",
            new InclusionIn(
                [
                    "domain" => [
                        "Mechanical",
                        "Virtual",
                    ]
                ]
            )
        );

        $validator->add(
            "name",
            new Uniqueness(
                [
                    "message" => "The robot name must be unique",
                ]
            )
        );

        return $this->validate($validator);
    }
}

The above example performs a validation using the built-in validator “InclusionIn”. It checks the value of the field “type” in a domain list. If the value is not included in the method then the validator will fail and return false.

For more information on validators, see the Validation documentation.

The idea of creating validators is make them reusable between several models. A validator can also be as simple as:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Message;

class Robots extends Model
{
    public function validation()
    {
        if ($this->type === "Old") {
            $message = new Message(
                "Sorry, old robots are not allowed anymore",
                "type",
                "MyType"
            );

            $this->appendMessage($message);

            return false;
        }

        return true;
    }
}
验证信息(Validation Messages)

Phalcon\Mvc\Model has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes.

Each message is an instance of Phalcon\Mvc\Model\Message and the set of messages generated can be retrieved with the getMessages() method. Each message provides extended information like the field name that generated the message or the message type:

<?php

if ($robot->save() === false) {
    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo "Message: ", $message->getMessage();
        echo "Field: ", $message->getField();
        echo "Type: ", $message->getType();
    }
}

Phalcon\Mvc\Model can generate the following types of validation messages:

Type Description
PresenceOf Generated when a field with a non-null attribute on the database is trying to insert/update a null value
ConstraintViolation Generated when a field part of a virtual foreign key is trying to insert/update a value that doesn’t exist in the referenced model
InvalidValue Generated when a validator failed because of an invalid value
InvalidCreateAttempt Produced when a record is attempted to be created but it already exists
InvalidUpdateAttempt Produced when a record is attempted to be updated but it doesn’t exist

The getMessages() method can be overridden in a model to replace/translate the default messages generated automatically by the ORM:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function getMessages()
    {
        $messages = [];

        foreach (parent::getMessages() as $message) {
            switch ($message->getType()) {
                case "InvalidCreateAttempt":
                    $messages[] = "The record cannot be created because it already exists";
                    break;

                case "InvalidUpdateAttempt":
                    $messages[] = "The record cannot be updated because it doesn't exist";
                    break;

                case "PresenceOf":
                    $messages[] = "The field " . $message->getField() . " is mandatory";
                    break;
            }
        }

        return $messages;
    }
}
验证失败事件(Validation Failed Events)

Another type of events are available when the data validation process finds any inconsistency:

Operation Name Explanation
Insert or Update notSaved Triggered when the INSERT or UPDATE operation fails for any reason
Insert, Delete or Update onValidationFails Triggered when any data manipulation operation fails

Working with Models (Advanced)

Hydration Modes

As mentioned previously, resultsets are collections of complete objects, this means that every returned result is an object representing a row in the database. These objects can be modified and saved again to persistence:

<?php

use Store\Toys\Robots;

$robots = Robots::find();

// Manipulating a resultset of complete objects
foreach ($robots as $robot) {
    $robot->year = 2000;

    $robot->save();
}

Sometimes records are obtained only to be presented to a user in read-only mode, in these cases it may be useful to change the way in which records are represented to facilitate their handling. The strategy used to represent objects returned in a resultset is called ‘hydration mode’:

<?php

use Phalcon\Mvc\Model\Resultset;
use Store\Toys\Robots;

$robots = Robots::find();

// Return every robot as an array
$robots->setHydrateMode(
    Resultset::HYDRATE_ARRAYS
);

foreach ($robots as $robot) {
    echo $robot["year"], PHP_EOL;
}

// Return every robot as a stdClass
$robots->setHydrateMode(
    Resultset::HYDRATE_OBJECTS
);

foreach ($robots as $robot) {
    echo $robot->year, PHP_EOL;
}

// Return every robot as a Robots instance
$robots->setHydrateMode(
    Resultset::HYDRATE_RECORDS
);

foreach ($robots as $robot) {
    echo $robot->year, PHP_EOL;
}

Hydration mode can also be passed as a parameter of ‘find’:

<?php

use Phalcon\Mvc\Model\Resultset;
use Store\Toys\Robots;

$robots = Robots::find(
    [
        "hydration" => Resultset::HYDRATE_ARRAYS,
    ]
);

foreach ($robots as $robot) {
    echo $robot["year"], PHP_EOL;
}
自动生成标识列(Auto-generated identity columns)

Some models may have identity columns. These columns usually are the primary key of the mapped table. Phalcon\Mvc\Model can recognize the identity column omitting it in the generated SQL INSERT, so the database system can generate an auto-generated value for it. Always after creating a record, the identity field will be registered with the value generated in the database system for it:

<?php

$robot->save();

echo "The generated id is: ", $robot->id;

Phalcon\Mvc\Model is able to recognize the identity column. Depending on the database system, those columns may be serial columns like in PostgreSQL or auto_increment columns in the case of MySQL.

PostgreSQL uses sequences to generate auto-numeric values, by default, Phalcon tries to obtain the generated value from the sequence “table_field_seq”, for example: robots_id_seq, if that sequence has a different name, the getSequenceName() method needs to be implemented:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function getSequenceName()
    {
        return "robots_sequence_name";
    }
}
忽略指定列的数据(Skipping Columns)

To tell Phalcon\Mvc\Model that always omits some fields in the creation and/or update of records in order to delegate the database system the assignation of the values by a trigger or a default:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        // Skips fields/columns on both INSERT/UPDATE operations
        $this->skipAttributes(
            [
                "year",
                "price",
            ]
        );

        // Skips only when inserting
        $this->skipAttributesOnCreate(
            [
                "created_at",
            ]
        );

        // Skips only when updating
        $this->skipAttributesOnUpdate(
            [
                "modified_in",
            ]
        );
    }
}

This will ignore globally these fields on each INSERT/UPDATE operation on the whole application. If you want to ignore different attributes on different INSERT/UPDATE operations, you can specify the second parameter (boolean) - true for replacement. Forcing a default value can be done in the following way:

<?php

use Store\Toys\Robots;

use Phalcon\Db\RawValue;

$robot = new Robots();

$robot->name       = "Bender";
$robot->year       = 1999;
$robot->created_at = new RawValue("default");

$robot->create();

A callback also can be used to create a conditional assignment of automatic default values:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;
use Phalcon\Db\RawValue;

class Robots extends Model
{
    public function beforeCreate()
    {
        if ($this->price > 10000) {
            $this->type = new RawValue("default");
        }
    }
}
Never use a Phalcon\Db\RawValue to assign external data (such as user input) or variable data. The value of these fields is ignored when binding parameters to the query. So it could be used to attack the application injecting SQL.
动态更新(Dynamic Update)

SQL UPDATE statements are by default created with every column defined in the model (full all-field SQL update). You can change specific models to make dynamic updates, in this case, just the fields that had changed are used to create the final SQL statement.

In some cases this could improve the performance by reducing the traffic between the application and the database server, this specially helps when the table has blob/text fields:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->useDynamicUpdate(true);
    }
}
独立的列映射(Independent Column Mapping)

The ORM supports an independent column map, which allows the developer to use different column names in the model to the ones in the table. Phalcon will recognize the new column names and will rename them accordingly to match the respective columns in the database. This is a great feature when one needs to rename fields in the database without having to worry about all the queries in the code. A change in the column map in the model will take care of the rest. For example:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $code;

    public $theName;

    public $theType;

    public $theYear;

    public function columnMap()
    {
        // Keys are the real names in the table and
        // the values their names in the application
        return [
            "id"       => "code",
            "the_name" => "theName",
            "the_type" => "theType",
            "the_year" => "theYear",
        ];
    }
}

Then you can use the new names naturally in your code:

<?php

use Store\Toys\Robots;

// Find a robot by its name
$robot = Robots::findFirst(
    "theName = 'Voltron'"
);

echo $robot->theName, "\n";

// Get robots ordered by type
$robot = Robots::find(
    [
        "order" => "theType DESC",
    ]
);

foreach ($robots as $robot) {
    echo "Code: ", $robot->code, "\n";
}

// Create a robot
$robot = new Robots();

$robot->code    = "10101";
$robot->theName = "Bender";
$robot->theType = "Industrial";
$robot->theYear = 2999;

$robot->save();

Take into consideration the following the next when renaming your columns:

  • References to attributes in relationships/validators must use the new names
  • Refer the real column names will result in an exception by the ORM

The independent column map allow you to:

  • Write applications using your own conventions
  • Eliminate vendor prefixes/suffixes in your code
  • Change column names without change your application code
记录快照(Record Snapshots)

Specific models could be set to maintain a record snapshot when they’re queried. You can use this feature to implement auditing or just to know what fields are changed according to the data queried from the persistence:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->keepSnapshots(true);
    }
}

When activating this feature the application consumes a bit more of memory to keep track of the original values obtained from the persistence. In models that have this feature activated you can check what fields changed:

<?php

use Store\Toys\Robots;

// Get a record from the database
$robot = Robots::findFirst();

// Change a column
$robot->name = "Other name";

var_dump($robot->getChangedFields()); // ["name"]

var_dump($robot->hasChanged("name")); // true

var_dump($robot->hasChanged("type")); // false
设置模式(Pointing to a different schema)

如果一个模型映射到一个在非默认的schemas/数据库中的表,你可以通过 setSchema() 方法去定义它:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->setSchema("toys");
    }
}
设置多个数据库(Setting multiple databases)

在Phalcon中,所有模型可以属于同一个数据库连接,也可以分属独立的数据库连接。实际上,当 Phalcon\Mvc\Model 需要连接数据库的时候,它在应用服务容器内请求”db”这个服务。 可以通过在 initialize() 方法内重写这个服务的设置。

<?php

use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
use Phalcon\Db\Adapter\Pdo\PostgreSQL as PostgreSQLPdo;

// This service returns a MySQL database
$di->set(
    "dbMysql",
    function () {
        return new MysqlPdo(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );
    }
);

// This service returns a PostgreSQL database
$di->set(
    "dbPostgres",
    function () {
        return new PostgreSQLPdo(
            [
                "host"     => "localhost",
                "username" => "postgres",
                "password" => "",
                "dbname"   => "invo",
            ]
        );
    }
);

然后,在 initialize() 方法内,我们为这个模型定义数据库连接。

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->setConnectionService("dbPostgres");
    }
}

另外Phalcon还提供了更多的灵活性,你可分别定义用来读取和写入的数据库连接。这对实现主从架构的数据库负载均衡非常有用。 (译者注:EvaEngine项目为使用Phalcon提供了更多的灵活性,推荐了解和使用)

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->setReadConnectionService("dbSlave");

        $this->setWriteConnectionService("dbMaster");
    }
}

另外ORM还可以通过根据当前查询条件来实现一个 ‘shard’ 选择器,来实现水平切分的功能。

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    /**
     * Dynamically selects a shard
     *
     * @param array $intermediate
     * @param array $bindParams
     * @param array $bindTypes
     */
    public function selectReadConnection($intermediate, $bindParams, $bindTypes)
    {
        // Check if there is a 'where' clause in the select
        if (isset($intermediate["where"])) {
            $conditions = $intermediate["where"];

            // Choose the possible shard according to the conditions
            if ($conditions["left"]["name"] === "id") {
                $id = $conditions["right"]["value"];

                if ($id > 0 && $id < 10000) {
                    return $this->getDI()->get("dbShard1");
                }

                if ($id > 10000) {
                    return $this->getDI()->get("dbShard2");
                }
            }
        }

        // Use a default shard
        return $this->getDI()->get("dbShard0");
    }
}

selectReadConnection() 方法用来选择正确的数据库连接,这个方法拦截任何新的查询操作:

<?php

use Store\Toys\Robots;

$robot = Robots::findFirst('id = 101');
注入服务到模型(Injecting services into Models)

你可能需要在模型中用到应用中注入的服务,下面的例子会教你如何去做:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function notSaved()
    {
        // Obtain the flash service from the DI container
        $flash = $this->getDI()->getFlash();

        $messages = $this->getMessages();

        // Show validation messages
        foreach ($messages as $message) {
            $flash->error($message);
        }
    }
}

每当 “create” 或者 “update” 操作失败时会触发 “notSave” 事件。所以我们从DI中获取 “flash” 服务并推送确认消息。这样的话,我们不需要每次在save之后去打印信息。

禁用或启用特性(Disabling/Enabling Features)

In the ORM we have implemented a mechanism that allow you to enable/disable specific features or options globally on the fly. According to how you use the ORM you can disable that you aren’t using. These options can also be temporarily disabled if required:

<?php

use Phalcon\Mvc\Model;

Model::setup(
    [
        "events"         => false,
        "columnRenaming" => false,
    ]
);

The available options are:

Option Description Default
events Enables/Disables callbacks, hooks and event notifications from all the models true
columnRenaming Enables/Disables the column renaming true
notNullValidations The ORM automatically validate the not null columns present in the mapped table true
virtualForeignKeys Enables/Disables the virtual foreign keys true
phqlLiterals Enables/Disables literals in the PHQL parser true
lateStateBinding Enables/Disables late state binding of the Mvc\Model::cloneResultMap() method false
独立的组件(Stand-Alone component)

Using Phalcon\Mvc\Model in a stand-alone mode can be demonstrated below:

<?php

use Phalcon\Di;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Db\Adapter\Pdo\Sqlite as Connection;
use Phalcon\Mvc\Model\Metadata\Memory as MetaData;

$di = new Di();

// Setup a connection
$di->set(
    "db",
    new Connection(
        [
            "dbname" => "sample.db",
        ]
    )
);

// Set a models manager
$di->set(
    "modelsManager",
    new ModelsManager()
);

// Use the memory meta-data adapter or other
$di->set(
    "modelsMetadata",
    new MetaData()
);

// Create a model
class Robots extends Model
{

}

// Use the model
echo Robots::count();

Phalcon 查询语言(Phalcon Query Language (PHQL))

Phalcon查询语言,PhalconQL或者简单的称之为PHQL,是一种面向对象的高级SQL语言,允许使用标准化的SQL编写操作语句。 PHQL实现了一个解析器(C编写)来把操作语句解析成RDBMS的语法。

为了达到高性能,Phalcon实现了一个和 SQLite 中相似的解析器。它只占用了非常低的内存,同时也是线程安全的。

The parser first checks the syntax of the pass PHQL statement, then builds an intermediate representation of the statement and finally it converts it to the respective SQL dialect of the target RDBMS.

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
范例(Usage Example)

为了更好的说明PHQL是如何使用的,在接下的例子中,我们定义了两个模型 “Cars” and “Brands”:

<?php

use Phalcon\Mvc\Model;

class Cars extends Model
{
    public $id;

    public $name;

    public $brand_id;

    public $price;

    public $year;

    public $style;

    /**
     * This model is mapped to the table sample_cars
     */
    public function getSource()
    {
        return "sample_cars";
    }

    /**
     * A car only has a Brand, but a Brand have many Cars
     */
    public function initialize()
    {
        $this->belongsTo("brand_id", "Brands", "id");
    }
}

然后每辆车(Car)都有一个品牌(Brand),一个品牌(Brand)却可以有很多辆车(Car):

<?php

use Phalcon\Mvc\Model;

class Brands extends Model
{
    public $id;

    public $name;

    /**
     * The model Brands is mapped to the "sample_brands" table
     */
    public function getSource()
    {
        return "sample_brands";
    }

    /**
     * A Brand can have many Cars
     */
    public function initialize()
    {
        $this->hasMany("id", "Cars", "brand_id");
    }
}
创建 PHQL 查询(Creating PHQL Queries)

PHQL查询可以通过实例化 Phalcon\Mvc\Model\Query 这个类来创建:

<?php

use Phalcon\Mvc\Model\Query;

// Instantiate the Query
$query = new Query(
    "SELECT * FROM Cars",
    $this->getDI()
);

// Execute the query returning a result if any
$cars = $query->execute();

在控制器或者视图中,通过 models manager 可以非常容易 create/execute PHQL查询:

<?php

// Executing a simple query
$query = $this->modelsManager->createQuery("SELECT * FROM Cars");
$cars  = $query->execute();

// With bound parameters
$query = $this->modelsManager->createQuery("SELECT * FROM Cars WHERE name = :name:");
$cars  = $query->execute(
    [
        "name" => "Audi",
    ]
);

或者使用一种更简单的执行方式:

<?php

// Executing a simple query
$cars = $this->modelsManager->executeQuery(
    "SELECT * FROM Cars"
);

// Executing with bound parameters
$cars = $this->modelsManager->executeQuery(
    "SELECT * FROM Cars WHERE name = :name:",
    [
        "name" => "Audi",
    ]
);
选取记录(Selecting Records)

和SQL类似,PHQL也允许使用SELECT来查询记录,但必须用模型类替换语句的表名:

<?php

$query = $manager->createQuery(
    "SELECT * FROM Cars ORDER BY Cars.name"
);

$query = $manager->createQuery(
    "SELECT Cars.name FROM Cars ORDER BY Cars.name"
);

带命名空间的模型类名也是允许的:

<?php

$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支持绝大多数的标准SQL语法,甚至非标准的SQL语法也支持,比如LIMIT:

<?php

$phql = "SELECT c.name FROM Cars AS c WHERE c.brand_id = 21 ORDER BY c.name LIMIT 100";

$query = $manager->createQuery($phql);
结果类型(Result Types)

查询结果的类型依赖于我们查询时列的类型,所以结果类型是多样化的。 如果你获得了一个完整的对象,那么这个对象是 Phalcon\Mvc\Model\Resultset\Simple 的实例。 这样的查询结果集是一组完整的模型对象:

<?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";
}

下面这种方式的查询结果集也是一样的:

<?php

$cars = Cars::find(
    [
        "order" => "name"
    ]
);

foreach ($cars as $car) {
    echo "Name: ", $car->name, "\n";
}

完整的对象中的数据可以被修改,并且可以重新保存在数据库中,因为它们在数据表里面本身就是一条完整的数据记录。 但是如下这种查询方式,就不会返回一个完整的对象:

<?php

$phql = "SELECT c.id, c.name FROM Cars AS c ORDER BY c.name";

$cars = $manager->executeQuery($phql);

foreach ($cars as $car) {
    echo "Name: ", $car->name, "\n";
}

我们只想要数据表中的一些字段,尽管返回的结果集对象仍然是 Phalcon\Mvc\Model\Resultset\Simple 的实例,但是却不能认为是一个完整的对象。 上述例子中,返回的结果集中的每个对象仅仅只有两个列对应的数据。

These values that don’t represent complete objects are what we call scalars. PHQL allows you to query all types of scalars: fields, functions, literals, expressions, etc..:

<?php

$phql = "SELECT CONCAT(c.id, ' ', c.name) AS id_name FROM Cars AS c ORDER BY c.name";

$cars = $manager->executeQuery($phql);

foreach ($cars as $car) {
    echo $car->id_name, "\n";
}

As we can query complete objects or scalars, we can also query both at once:

<?php

$phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c ORDER BY c.name";

$result = $manager->executeQuery($phql);

The result in this case is an object Phalcon\Mvc\Model\Resultset\Complex. This allows access to both complete objects and scalars at once:

<?php

foreach ($result as $row) {
    echo "Name: ", $row->cars->name, "\n";
    echo "Price: ", $row->cars->price, "\n";
    echo "Taxes: ", $row->taxes, "\n";
}

Scalars are mapped as properties of each “row”, while complete objects are mapped as properties with the name of its related model.

连接(Joins)

通过PHQL可以非常方便的从多个模型中请求数据记录。PHQL支持绝大多数的JOIN操作。As we defined relationships in the models, PHQL adds these conditions automatically:

<?php

$phql = "SELECT Cars.name AS car_name, Brands.name AS brand_name FROM Cars JOIN Brands";

$rows = $manager->executeQuery($phql);

foreach ($rows as $row) {
    echo $row->car_name, "\n";
    echo $row->brand_name, "\n";
}

By default, an INNER JOIN is assumed. You can specify the type of JOIN in the query:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT Cars.*, Brands.* FROM Cars LEFT JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT Cars.*, Brands.* FROM Cars LEFT OUTER JOIN Brands";
$rows = $manager->executeQuery($phql);

$phql = "SELECT Cars.*, Brands.* FROM Cars CROSS JOIN Brands";
$rows = $manager->executeQuery($phql);

也可以手动设置JOIN条件:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars INNER JOIN Brands ON Brands.id = Cars.brands_id";

$rows = $manager->executeQuery($phql);

Also, the joins can be created using multiple tables in the FROM clause:

<?php

$phql = "SELECT Cars.*, Brands.* FROM Cars, Brands WHERE Brands.id = Cars.brands_id";

$rows = $manager->executeQuery($phql);

foreach ($rows as $row) {
    echo "Car: ", $row->cars->name, "\n";
    echo "Brand: ", $row->brands->name, "\n";
}

If an alias is used to rename the models in the query, those will be used to name the attributes in the every row of the result:

<?php

$phql = "SELECT c.*, b.* FROM Cars c, Brands b WHERE b.id = c.brands_id";

$rows = $manager->executeQuery($phql);

foreach ($rows as $row) {
    echo "Car: ", $row->c->name, "\n";
    echo "Brand: ", $row->b->name, "\n";
}

When the joined model has a many-to-many relation to the ‘from’ model, the intermediate model is implicitly added to the generated query:

<?php

$phql = "SELECT Artists.name, Songs.name FROM Artists " .
        "JOIN Songs WHERE Artists.genre = 'Trip-Hop'";

$result = $this->modelsManager->executeQuery($phql);

This code executes the following SQL in MySQL:

SELECT `artists`.`name`, `songs`.`name` FROM `artists`
INNER JOIN `albums` ON `albums`.`artists_id` = `artists`.`id`
INNER JOIN `songs` ON `albums`.`songs_id` = `songs`.`id`
WHERE `artists`.`genre` = 'Trip-Hop'
聚合(Aggregations)

The following examples show how to use aggregations in PHQL:

<?php

// How much are the prices of all the cars?
$phql = "SELECT SUM(price) AS summatory FROM Cars";
$row  = $manager->executeQuery($phql)->getFirst();
echo $row['summatory'];

// How many cars are by each brand?
$phql = "SELECT Cars.brand_id, COUNT(*) FROM Cars GROUP BY Cars.brand_id";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row) {
    echo $row->brand_id, ' ', $row["1"], "\n";
}

// How many cars are by each brand?
$phql = "SELECT Brands.name, COUNT(*) FROM Cars JOIN Brands GROUP BY 1";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row) {
    echo $row->name, ' ', $row["1"], "\n";
}

$phql = "SELECT MAX(price) AS maximum, MIN(price) AS minimum FROM Cars";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row) {
    echo $row["maximum"], ' ', $row["minimum"], "\n";
}

// Count distinct used brands
$phql = "SELECT COUNT(DISTINCT brand_id) AS brandId FROM Cars";
$rows = $manager->executeQuery($phql);
foreach ($rows as $row) {
    echo $row->brandId, "\n";
}
条件(Conditions)

Conditions allow us to filter the set of records we want to query. The WHERE clause allows to do that:

<?php

// Simple conditions
$phql = "SELECT * FROM Cars WHERE Cars.name = 'Lamborghini Espada'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.price > 10000";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE TRIM(Cars.name) = 'Audi R8'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.name LIKE 'Ferrari%'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.name NOT LIKE 'Ferrari%'";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.price IS NULL";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id IN (120, 121, 122)";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id NOT IN (430, 431)";
$cars = $manager->executeQuery($phql);

$phql = "SELECT * FROM Cars WHERE Cars.id BETWEEN 1 AND 100";
$cars = $manager->executeQuery($phql);

Also, as part of PHQL, prepared parameters automatically escape the input data, introducing more security:

<?php

$phql = "SELECT * FROM Cars WHERE Cars.name = :name:";
$cars = $manager->executeQuery(
    $phql,
    [
        "name" => "Lamborghini Espada"
    ]
);

$phql = "SELECT * FROM Cars WHERE Cars.name = ?0";
$cars = $manager->executeQuery(
    $phql,
    [
        0 => "Lamborghini Espada"
    ]
);
插入数据(Inserting Data)

With PHQL it’s possible to insert data using the familiar INSERT statement:

<?php

// Inserting without columns
$phql = "INSERT INTO Cars VALUES (NULL, 'Lamborghini Espada', "
      . "7, 10000.00, 1969, 'Grand Tourer')";
$manager->executeQuery($phql);

// Specifying columns to insert
$phql = "INSERT INTO Cars (name, brand_id, year, style) "
      . "VALUES ('Lamborghini Espada', 7, 1969, 'Grand Tourer')";
$manager->executeQuery($phql);

// Inserting using placeholders
$phql = "INSERT INTO Cars (name, brand_id, year, style) "
      . "VALUES (:name:, :brand_id:, :year:, :style)";
$manager->executeQuery(
    $phql,
    [
        "name"     => "Lamborghini Espada",
        "brand_id" => 7,
        "year"     => 1969,
        "style"    => "Grand Tourer",
    ]
);

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:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Message;

class Cars extends Model
{
    public function beforeCreate()
    {
        if ($this->price < 10000) {
            $this->appendMessage(
                new Message("A car cannot cost less than $ 10,000")
            );

            return false;
        }
    }
}

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. By checking the status of the insertion we can print any validation messages generated internally:

<?php

$phql = "INSERT INTO Cars VALUES (NULL, 'Nissan Versa', 7, 9999.00, 2015, 'Sedan')";

$result = $manager->executeQuery($phql);

if ($result->success() === false) {
    foreach ($result->getMessages() as $message) {
        echo $message->getMessage();
    }
}
更新数据(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.

<?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);

// Updating multiples rows
$phql = "UPDATE Cars SET price = 7000.00, type = 'Sedan' WHERE brands_id > 5";
$manager->executeQuery($phql);

// Using placeholders
$phql = "UPDATE Cars SET price = ?0, type = ?1 WHERE brands_id > ?2";
$manager->executeQuery(
    $phql,
    [
        0 => 7000.00,
        1 => 'Sedan',
        2 => 5,
    ]
);

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

This way of operation allows that events, virtual foreign keys and validations take part of the updating process. In summary, the following code:

<?php

$phql = "UPDATE Cars SET price = 15000.00 WHERE id > 101";

$result = $manager->executeQuery($phql);

if ($result->success() === false) {
    $messages = $result->getMessages();

    foreach ($messages as $message) {
        echo $message->getMessage();
    }
}

is somewhat equivalent to:

<?php

$messages = null;

$process = function () use (&$messages) {
    $cars = Cars::find("id > 101");

    foreach ($cars as $car) {
        $car->price = 15000;

        if ($car->save() === false) {
            $messages = $car->getMessages();

            return false;
        }
    }

    return true;
};

$success = $process();
删除数据(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);

// Using placeholders
$phql = "DELETE FROM Cars WHERE id BETWEEN :initial: AND :final:";
$manager->executeQuery(
    $phql,
    [
        "initial" => 1,
        "final"   => 100,
    ]
);

DELETE operations are also executed in two phases like UPDATEs. To check if the deletion produces any validation messages you should check the status code returned:

<?php

// Deleting multiple rows
$phql = "DELETE FROM Cars WHERE id > 100";

$result = $manager->executeQuery($phql);

if ($result->success() === false) {
    $messages = $result->getMessages();

    foreach ($messages as $message) {
        echo $message->getMessage();
    }
}
使用查询构建器创建查询(Creating queries using the Query Builder)

A builder is available to create PHQL queries without the need to write PHQL statements, also providing IDE facilities:

<?php

// Getting a whole set
$robots = $this->modelsManager->createBuilder()
    ->from("Robots")
    ->join("RobotsParts")
    ->orderBy("Robots.name")
    ->getQuery()
    ->execute();

// Getting the first row
$robots = $this->modelsManager->createBuilder()
    ->from("Robots")
    ->join("RobotsParts")
    ->orderBy("Robots.name")
    ->getQuery()
    ->getSingleResult();

That is the same as:

<?php

$phql = "SELECT Robots.* FROM Robots JOIN RobotsParts p ORDER BY Robots.name LIMIT 20";

$result = $manager->executeQuery($phql);

More examples of the builder:

<?php

// 'SELECT Robots.* FROM Robots';
$builder->from("Robots");

// 'SELECT Robots.*, RobotsParts.* FROM Robots, RobotsParts';
$builder->from(
    [
        "Robots",
        "RobotsParts",
    ]
);

// 'SELECT * FROM Robots';
$phql = $builder->columns("*")
                ->from("Robots");

// 'SELECT id FROM Robots';
$builder->columns("id")
        ->from("Robots");

// 'SELECT id, name FROM Robots';
$builder->columns(["id", "name"])
        ->from("Robots");

// 'SELECT Robots.* FROM Robots WHERE Robots.name = "Voltron"';
$builder->from("Robots")
        ->where("Robots.name = 'Voltron'");

// 'SELECT Robots.* FROM Robots WHERE Robots.id = 100';
$builder->from("Robots")
        ->where(100);

// 'SELECT Robots.* FROM Robots WHERE Robots.type = "virtual" AND Robots.id > 50';
$builder->from("Robots")
        ->where("type = 'virtual'")
        ->andWhere("id > 50");

// 'SELECT Robots.* FROM Robots WHERE Robots.type = "virtual" OR Robots.id > 50';
$builder->from("Robots")
        ->where("type = 'virtual'")
        ->orWhere("id > 50");

// 'SELECT Robots.* FROM Robots GROUP BY Robots.name';
$builder->from("Robots")
        ->groupBy("Robots.name");

// 'SELECT Robots.* FROM Robots GROUP BY Robots.name, Robots.id';
$builder->from("Robots")
        ->groupBy(["Robots.name", "Robots.id"]);

// 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name';
$builder->columns(["Robots.name", "SUM(Robots.price)"])
    ->from("Robots")
    ->groupBy("Robots.name");

// 'SELECT Robots.name, SUM(Robots.price) FROM Robots GROUP BY Robots.name HAVING SUM(Robots.price) > 1000';
$builder->columns(["Robots.name", "SUM(Robots.price)"])
    ->from("Robots")
    ->groupBy("Robots.name")
    ->having("SUM(Robots.price) > 1000");

// 'SELECT Robots.* FROM Robots JOIN RobotsParts';
$builder->from("Robots")
    ->join("RobotsParts");

// 'SELECT Robots.* FROM Robots JOIN RobotsParts AS p';
$builder->from("Robots")
    ->join("RobotsParts", null, "p");

// 'SELECT Robots.* FROM Robots JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p';
$builder->from("Robots")
    ->join("RobotsParts", "Robots.id = RobotsParts.robots_id", "p");

// 'SELECT Robots.* FROM Robots
// JOIN RobotsParts ON Robots.id = RobotsParts.robots_id AS p
// JOIN Parts ON Parts.id = RobotsParts.parts_id AS t';
$builder->from("Robots")
    ->join("RobotsParts", "Robots.id = RobotsParts.robots_id", "p")
    ->join("Parts", "Parts.id = RobotsParts.parts_id", "t");

// 'SELECT r.* FROM Robots AS r';
$builder->addFrom("Robots", "r");

// 'SELECT Robots.*, p.* FROM Robots, Parts AS p';
$builder->from("Robots")
    ->addFrom("Parts", "p");

// 'SELECT r.*, p.* FROM Robots AS r, Parts AS p';
$builder->from(["r" => "Robots"])
        ->addFrom("Parts", "p");

// 'SELECT r.*, p.* FROM Robots AS r, Parts AS p';
$builder->from(["r" => "Robots", "p" => "Parts"]);

// 'SELECT Robots.* FROM Robots LIMIT 10';
$builder->from("Robots")
    ->limit(10);

// 'SELECT Robots.* FROM Robots LIMIT 10 OFFSET 5';
$builder->from("Robots")
        ->limit(10, 5);

// 'SELECT Robots.* FROM Robots WHERE id BETWEEN 1 AND 100';
$builder->from("Robots")
        ->betweenWhere("id", 1, 100);

// 'SELECT Robots.* FROM Robots WHERE id IN (1, 2, 3)';
$builder->from("Robots")
        ->inWhere("id", [1, 2, 3]);

// 'SELECT Robots.* FROM Robots WHERE id NOT IN (1, 2, 3)';
$builder->from("Robots")
        ->notInWhere("id", [1, 2, 3]);

// 'SELECT Robots.* FROM Robots WHERE name LIKE '%Art%';
$builder->from("Robots")
        ->where("name LIKE :name:", ["name" => "%" . $name . "%"]);

// 'SELECT r.* FROM Store\Robots WHERE r.name LIKE '%Art%';
$builder->from(['r' => 'Store\Robots'])
        ->where("r.name LIKE :name:", ["name" => "%" . $name . "%"]);
绑定参数(Bound Parameters)

Bound parameters in the query builder can be set as the query is constructed or past all at once when executing:

<?php

// Passing parameters in the query construction
$robots = $this->modelsManager->createBuilder()
    ->from("Robots")
    ->where("name = :name:", ["name" => $name])
    ->andWhere("type = :type:", ["type" => $type])
    ->getQuery()
    ->execute();

// Passing parameters in query execution
$robots = $this->modelsManager->createBuilder()
    ->from("Robots")
    ->where("name = :name:")
    ->andWhere("type = :type:")
    ->getQuery()
    ->execute(["name" => $name, "type" => $type]);
禁止使用字面值(Disallow literals in PHQL)

Literals can be disabled in PHQL, this means that directly using strings, numbers and boolean values in PHQL strings will be disallowed. If PHQL statements are created embedding external data on them, this could open the application to potential SQL injections:

<?php

$login = 'voltron';

$phql = "SELECT * FROM Models\Users WHERE login = '$login'";

$result = $manager->executeQuery($phql);

If $login is changed to ' OR '' = ', the produced PHQL is:

SELECT * FROM Models\Users WHERE login = '' OR '' = ''

Which is always true no matter what the login stored in the database is.

If literals are disallowed strings can be used as part of a PHQL statement, thus an exception will be thrown forcing the developer to use bound parameters. The same query can be written in a secure way like this:

<?php

$phql = "SELECT Robots.* FROM Robots WHERE Robots.name = :name:";

$result = $manager->executeQuery(
    $phql,
    [
        "name" => $name,
    ]
);

You can disallow literals in the following way:

<?php

use Phalcon\Mvc\Model;

Model::setup(
    [
        "phqlLiterals" => false
    ]
);

Bound parameters can be used even if literals are allowed or not. Disallowing them is just another security decision a developer could take in web applications.

转义保留字(Escaping Reserved Words)

PHQL has a few reserved words, if you want to use any of them as attributes or models names, you need to escape those words using the cross-database escaping delimiters ‘[‘ and ‘]’:

<?php

$phql   = "SELECT * FROM [Update]";
$result = $manager->executeQuery($phql);

$phql   = "SELECT id, [Like] FROM Posts";
$result = $manager->executeQuery($phql);

The delimiters are dynamically translated to valid delimiters depending on the database system where the application is currently running on.

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
使用原生 SQL(Using Raw SQL)

A database system could offer specific SQL extensions that aren’t supported by PHQL, in this case, a raw SQL can be appropriate:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Resultset\Simple as Resultset;

class Robots extends Model
{
    public static function findByCreateInterval()
    {
        // A raw SQL statement
        $sql = "SELECT * FROM robots WHERE id > 0";

        // Base model
        $robot = new Robots();

        // Execute the query
        return new Resultset(
            null,
            $robot,
            $robot->getReadConnection()->query($sql)
        );
    }
}

If Raw SQL queries are common in your application a generic method could be added to your model:

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Resultset\Simple as Resultset;

class Robots extends Model
{
    public static function findByRawSql($conditions, $params = null)
    {
        // A raw SQL statement
        $sql = "SELECT * FROM robots WHERE $conditions";

        // Base model
        $robot = new Robots();

        // Execute the query
        return new Resultset(
            null,
            $robot,
            $robot->getReadConnection()->query($sql, $params)
        );
    }
}

The above findByRawSql could be used as follows:

<?php

$robots = Robots::findByRawSql(
    "id > ?",
    [
        10
    ]
);
注意事项(Troubleshooting)

Some things to keep in mind when using PHQL:

  • Classes are case-sensitive, if a class is not defined with the same name as it was created this could lead to an unexpected behavior in operating systems with case-sensitive file systems such as Linux.
  • Correct charset must be defined in the connection to bind parameters with success.
  • Aliased classes aren’t replaced by full namespaced classes since this only occurs in PHP code and not inside strings.
  • If column renaming is enabled avoid using column aliases with the same name as columns to be renamed, this may confuse the query resolver.

缓存对象关系映射(Caching in the ORM)

现实中的每个应用都不同,一些应用的模型数据经常改变而另一些模型的数据几乎不同。访问数据库在很多时候对我们应用的来说 是个瓶颈。这是由于我们每次访问应用时都会和数据库数据通信,和数据库进行通信的代价是很大的。因此在必要时我们可以通过增加 缓存层来获取更高的性能。 本章内容的重点即是探讨实施缓存来提高性能的可行性。Phalcon框架给我们提供了灵活的缓存技术来实现我们的应用缓存。

缓存结果集(Caching Resultsets)

一个非常可行的方案是我们可以为那些不经常改变且经常访问的数据库数据进行缓存,比如把他们放入内存,这样可以加快程序的执行速度。

Phalcon\Mvc\Model 需要使用缓存数据的服务时Model可以直接从DI中取得此缓存服务modelsCache(惯例名).

Phalcon提供了一个组件(服务)可以用来 缓存 任何种类的数据,下面我们会解释如何在model使用它。第一步我们要在启动文件注册 这个服务:

<?php

use Phalcon\Cache\Frontend\Data as FrontendData;
use Phalcon\Cache\Backend\Memcache as BackendMemcache;

// 设置模型缓存服务
$di->set(
    "modelsCache",
    function () {
        // 默认缓存时间为一天
        $frontCache = new FrontendData(
            [
                "lifetime" => 86400,
            ]
        );

        // Memcached连接配置 这里使用的是Memcache适配器
        $cache = new BackendMemcache(
            $frontCache,
            [
                "host" => "localhost",
                "port" => "11211",
            ]
        );

        return $cache;
    }
);

在注册缓存服务时我们可以按照我们的需要进行配置。一旦完成正确的缓存设置之后,我们可以按如下的方式缓存查询的结果了:

<?php

// 直接取Products模型里的数据(未缓存)
$products = Products::find();

// 缓存查询结果.缓存时间为默认1天。
$products = Products::find(
    [
        "cache" => [
            "key" => "my-cache",
        ],
    ]
);

// 缓存查询结果时间为300秒
$products = Products::find(
    [
        "cache" => [
            "key"      => "my-cache",
            "lifetime" => 300,
        ],
    ]
);

// Use the 'cache' service from the DI instead of 'modelsCache'
$products = Products::find(
    [
        "cache" => [
            "key"          => "my-cache",
            "cacheService" => "cache",
        ],
    ]
);

这里我们也可以缓存关联表的数据:
<?php

// Query some post
$post = Post::findFirst();

// Get comments related to a post, also cache it
$comments = $post->getComments(
    [
        "cache" => [
            "key" => "my-key",
        ],
    ]
);

// Get comments related to a post, setting lifetime
$comments = $post->getComments(
    [
        "cache" => [
            "key"      => "my-key",
            "lifetime" => 3600,
        ],
    ]
);

如果想删除已经缓存的结果,则只需要使用前面指定的缓存的键值进行删除即可。

注意并不是所有的结果都必须缓存下来。那些经常改变的数据就不应该被缓存,这样做只会影响应用的性能。另外对于那些特别大的 不易变的数据集,开发者应用根据实际情况进行选择是否进行缓存。

强制缓存(Forcing Cache)

前面的例子中我们在 Phalcon\Mvc\Model 中使用框架内建的缓存组件。为实现强制缓存我们传递了cache作为参数:

<?php

// 缓存查询结果5分钟
$products = Products::find(
    [
        "cache" => [
            "key"      => "my-cache",
            "lifetime" => 300,
        ],
    ]
);

这给了我们自由选择需要缓存的查询结果,但是如果我们想对模型中的所有查询结果进行缓存,那么我们可以重写:code:find()/:code:`findFirst()`方法:

<?php

use Phalcon\Mvc\Model;

class Robots extends Model
{
    /**
     * Implement a method that returns a string key based
     * on the query parameters
     */
    protected static function _createKey($parameters)
    {
        $uniqueKey = [];

        foreach ($parameters as $key => $value) {
            if (is_scalar($value)) {
                $uniqueKey[] = $key . ":" . $value;
            } elseif (is_array($value)) {
                $uniqueKey[] = $key . ":[" . self::_createKey($value) . "]";
            }
        }

        return join(",", $uniqueKey);
    }

    public static function find($parameters = null)
    {
        // Convert the parameters to an array
        if (!is_array($parameters)) {
            $parameters = [$parameters];
        }

        // Check if a cache key wasn't passed
        // and create the cache parameters
        if (!isset($parameters["cache"])) {
            $parameters["cache"] = [
                "key"      => self::_createKey($parameters),
                "lifetime" => 300,
            ];
        }

        return parent::find($parameters);
    }

    public static function findFirst($parameters = null)
    {
        // ...
    }
}

访问数据要远比计算key值慢的多,我们在这里定义自己需要的key生成方式。注意好的键可以避免冲突,这样就可以依据不同的key值 取得不同的缓存结果。

这样我们可以对每个模型的缓存进行完全的控制,如果其他的模型也需要共用此缓存,可以建立一个模型缓存基类:

<?php

use Phalcon\Mvc\Model;

class CacheableModel extends Model
{
    protected static function _createKey($parameters)
    {
        // ... Create a cache key based on the parameters
    }

    public static function find($parameters = null)
    {
        // ... Custom caching strategy
    }

    public static function findFirst($parameters = null)
    {
        // ... Custom caching strategy
    }
}

然后把这个类作为其它缓存类的基类:

<?php

class Robots extends CacheableModel
{

}
缓存 PHQL 查询(Caching PHQL Queries)

ORM中的所有查询,不论多高级的查询方法,内部都是通过PHQL进行实现的。PHQL可以让我们非常自由的创建各种查询,当然这些查询也可以被缓存:

<?php

$phql = "SELECT * FROM Cars WHERE name = :name:";

$query = $this->modelsManager->createQuery($phql);

$query->cache(
    [
        "key"      => "cars-by-name",
        "lifetime" => 300,
    ]
);

$cars = $query->execute(
    [
        "name" => "Audi",
    ]
);
基于条件的缓存(Caching based on Conditions)

此例中,根据不同的条件实施缓存. We might decide that the cache backend should be determined by the primary key:

类型 缓存
1 - 10000 mongo1
10000 - 20000 mongo2
> 20000 mongo3

最简单的方式即是为模型类添加一个静态的方法,此方法中我们指定要使用的缓存:

<?php

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public static function queryCache($initial, $final)
    {
        if ($initial >= 1 && $final < 10000) {
            $service = "mongo1";
        } elseif ($initial >= 10000 && $final <= 20000) {
            $service = "mongo2";
        } elseif ($initial > 20000) {
            $service = "mongo3";
        }

        return self::find(
            [
                "id >= " . $initial . " AND id <= " . $final,
                "cache" => [
                    "service" => $service,
                ],
            ]
        );
    }
}

这个方法是可以解决问题,不过如果我们需要添加其它的参数比如排序或条件等等,我们还要创建更复杂的方法。另外当我们使用:code:find()/:code:`findFirst()`来查询关联数据时此方法亦会失效:

<?php

$robots = Robots::find("id < 1000");
$robots = Robots::find("id > 100 AND type = 'A'");
$robots = Robots::find("(id > 100 AND type = 'A') AND id < 2000");

$robots = Robots::find(
    [
        "(id > ?0 AND type = 'A') AND id < ?1",
        "bind"  => [100, 2000],
        "order" => "type",
    ]
);

为了实现这个,我们需要拦截中间语言解析,然后书写相关的代码以定制缓存: 首先我们需要创建自定义的创建器,然后我们可以使用它来创建自己定义的查询:

<?php

use Phalcon\Mvc\Model\Query\Builder as QueryBuilder;

class CustomQueryBuilder extends QueryBuilder
{
    public function getQuery()
    {
        $query = new CustomQuery($this->getPhql());

        $query->setDI($this->getDI());

        return $query;
    }
}

这里我们返回的是CustomQuery而不是不直接的返回 Phalcon\Mvc\Model\Query, 类定义如下所示:

<?php

use Phalcon\Mvc\Model\Query as ModelQuery;

class CustomQuery extends ModelQuery
{
    /**
     * The execute method is overridden
     */
    public function execute($params = null, $types = null)
    {
        // Parse the intermediate representation for the SELECT
        $ir = $this->parse();

        // Check if the query has conditions
        if (isset($ir["where"])) {
            // The fields in the conditions can have any order
            // We need to recursively check the conditions tree
            // to find the info we're looking for
            $visitor = new CustomNodeVisitor();

            // Recursively visits the nodes
            $visitor->visit($ir["where"]);

            $initial = $visitor->getInitial();
            $final   = $visitor->getFinal();

            // Select the cache according to the range
            // ...

            // Check if the cache has data
            // ...
        }

        // Execute the query
        $result = $this->_executeSelect($ir, $params, $types);

        // Cache the result
        // ...

        return $result;
    }
}

这里我们实现了一个帮助类,用递归的方式来检查条件中的查询字段,方便我们了解需要使用缓存的范围(即检查条件以确认实施查询缓存的范围):

<?php

class CustomNodeVisitor
{
    protected $_initial = 0;

    protected $_final = 25000;

    public function visit($node)
    {
        switch ($node["type"]) {
            case "binary-op":
                $left  = $this->visit($node["left"]);
                $right = $this->visit($node["right"]);

                if (!$left || !$right) {
                    return false;
                }

                if ($left === "id") {
                    if ($node["op"] === ">") {
                        $this->_initial = $right;
                    }

                    if ($node["op"] === "=") {
                        $this->_initial = $right;
                    }

                    if ($node["op"] === ">=") {
                        $this->_initial = $right;
                    }

                    if ($node["op"] === "<") {
                        $this->_final = $right;
                    }

                    if ($node["op"] === "<=") {
                        $this->_final = $right;
                    }
                }

                break;

            case "qualified":
                if ($node["name"] === "id") {
                    return "id";
                }

                break;

            case "literal":
                return $node["value"];

            default:
                return false;
        }
    }

    public function getInitial()
    {
        return $this->_initial;
    }

    public function getFinal()
    {
        return $this->_final;
    }
}

最后,我们替换Robots模型中的查询方法,以使用我们创建的自定义类:

<?php

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public static function find($parameters = null)
    {
        if (!is_array($parameters)) {
            $parameters = [$parameters];
        }

        $builder = new CustomQueryBuilder($parameters);

        $builder->from(get_called_class());

        $query = $builder->getQuery();

        if (isset($parameters["bind"])) {
            return $query->execute($parameters["bind"]);
        } else {
            return $query->execute();
        }
    }
}
缓存 PHQL 查询计划(Caching of PHQL planning)

像大多数现代的操作系统一样PHQL内部会缓存执行计划,如果同样的语句多次执行,PHQL会使用之前生成的查询计划以提升系统的性能, 对开发者来说只采用绑定参数的形式传递参数即可实现:

<?php

for ($i = 1; $i <= 10; $i++) {
    $phql = "SELECT * FROM Store\Robots WHERE id = " . $i;

    $robots = $this->modelsManager->executeQuery($phql);

    // ...
}

上面的例子中,Phalcon产生了10个查询计划,这导致了应用的内存使用量增加。重写以上代码,我们使用绑定参数的这个优点可以减少系统和数据库的过多操作:

<?php

$phql = "SELECT * FROM Store\Robots WHERE id = ?0";

for ($i = 1; $i <= 10; $i++) {
    $robots = $this->modelsManager->executeQuery(
        $phql,
        [
            $i,
        ]
    );

    // ...
}

使用PHQL查询亦可以提升查询性能:

<?php

$phql = "SELECT * FROM Store\Robots WHERE id = ?0";

$query = $this->modelsManager->createQuery($phql);

for ($i = 1; $i <= 10; $i++) {
    $robots = $query->execute(
        $phql,
        [
            $i,
        ]
    );

    // ...
}

预先准备的查询语句 的查询计划亦可以被大多数的数据库所缓存,这样可以减少执行的时间,也可以使我们的系统免受 SQL注入 的影响。

对象文档映射 ODM (Object-Document Mapper)

除了可以 映射关系数据库的表 之外,Phalcon还可以使用NoSQL数据库如MongoDB等。Phalcon中的ODM具有可以非常容易的实现如下功能:CRUD,事件,验证等。

因为NoSQL数据库中无sql查询及计划等操作故可以提高数据操作的性能。再者,由于无SQL语句创建的操作故可以减少SQL注入的危险。

当前Phalcon中支持的NosSQL数据库如下:

名称 描述
MongoDB MongoDB是一个稳定的高性能的开源的NoSQL数据
创建模型(Creating Models)

NoSQL中的模型类扩展自 Phalcon\Mvc\Collection.模型必须要放入模型文件夹中而且每个模型文件必须只能有一个模型类; 模型类名应该为小驼峰法书写:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{

}

如果PHP版本为5.4/5.5或更高版本,为了提高性能节省内存开销,最好在模型类文件中定义每个字段。

模型Robots默认和数据库中的robots表格映射。如果想使用别的名字映射数据库中的表格则只需要重写 setSource() 方法即可:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function initialize()
    {
        $this->setSource("the_robots");
    }
}
理解文档对象(Understanding Documents To Objects)

每个模型的实例和数据库表中的一个文档(记录)相对应。我们可以非常容易的通过读取对象属性来访问表格的数据。例如访问robots表格:

$ mongo test
MongoDB shell version: 1.8.2
connecting to: test
> db.robots.find()
{ "_id" : ObjectId("508735512d42b8c3d15ec4e1"), "name" : "Astro Boy", "year" : 1952,
    "type" : "mechanical" }
{ "_id" : ObjectId("5087358f2d42b8c3d15ec4e2"), "name" : "Bender", "year" : 1999,
    "type" : "mechanical" }
{ "_id" : ObjectId("508735d32d42b8c3d15ec4e3"), "name" : "Wall-E", "year" : 2008 }
>
模型中使用命名空间(Models in Namespaces)

我们在这里可以使用命名空间来避免类名冲突。这个例子中我们使用:code:`setSource()`方法来标明要使用的数据库表:

<?php

namespace Store\Toys;

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function initialize()
    {
        $this->setSource("robots");
    }
}

我们可以通过对象的ID查找到对象然后打印出其名字:

<?php

// Find record with _id = "5087358f2d42b8c3d15ec4e2"
$robot = Robots::findById("5087358f2d42b8c3d15ec4e2");

// Prints "Bender"
echo $robot->name;

一旦记录被加载到内存中,我们就可以对这些数据进行修改了,修改之后还可以保存:

<?php

$robot = Robots::findFirst(
    [
        [
            "name" => "Astro Boy",
        ]
    ]
);

$robot->name = "Voltron";

$robot->save();
设置连接(Setting a Connection)

这里的MongoDB服务是从服务容器中取得的。默认,Phalcon会使mongo作服务名:

<?php

// Simple database connection to localhost
$di->set(
    "mongo",
    function () {
        $mongo = new MongoClient();

        return $mongo->selectDB("store");
    },
    true
);

// Connecting to a domain socket, falling back to localhost connection
$di->set(
    "mongo",
    function () {
        $mongo = new MongoClient(
            "mongodb:///tmp/mongodb-27017.sock,localhost:27017"
        );

        return $mongo->selectDB("store");
    },
    true
);
查找文档(Finding Documents)

Phalcon\Mvc\Collection 依赖于Mongo的PHP扩展,这样我们就可以直接从数据库中查询出文档记录然后Phalcon会 透明的(我们无需关心过程和方法)为我们转换为模型的实例。 Phalcon\Mvc\Collection

<?php

// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find(
    [
        [
            "type" => "mechanical",
        ]
    ]
);
echo "There are ", count($robots), "\n";

// Get and print mechanical robots ordered by name upward
$robots = Robots::find(
    [
        [
            "type" => "mechanical",
        ],
        "sort" => [
            "name" => 1,
        ],
    ]
);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 mechanical robots ordered by name
$robots = Robots::find(
    [
        [
            "type" => "mechanical",
        ],
        "sort"  => [
            "name" => 1,
        ],
        "limit" => 100,
    ]
);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

这里我们可以使用 findFirst() 来取得配置查询的第一条记录:

<?php

// What's the first robot in robots collection?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";

// What's the first mechanical robot in robots collection?
$robot = Robots::findFirst(
    [
        [
            "type" => "mechanical",
        ]
    ]
);
echo "The first mechanical robot name is ", $robot->name, "\n";

find()findFirst() 方法都接收一个关联数据组为查询的条件:

<?php

// First robot where type = "mechanical" and year = "1999"
$robot = Robots::findFirst(
    [
        "conditions" => [
            "type" => "mechanical",
            "year" => "1999",
        ],
    ]
);

// All virtual robots ordered by name downward
$robots = Robots::find(
    [
        "conditions" => [
            "type" => "virtual",
        ],
        "sort" => [
            "name" => -1,
        ],
    ]
);

可用的查询选项:

参数 描述 例子
conditions (条件) 搜索条件,用于取只满足要求的数,默认情况下Phalcon_model会假定关联数据的第一个参数为查询条 "conditions" => array('$gt' => 1990)
fields (字段) 若指定则返回指定的字段而非全部字段,当设置此字段时会返回非完全版本的对象 "fields" => array('name' => true)
sort (排序) 这个选项用来对查询结果进行排序,使用一个或多个字段作为排序的标准,使用数组来表格,1代表升序,-1代表降 "order" => array("name" => -1, "status" => 1)
limit (限制) 限制查询结果集到指定的范围 "limit" => 10
skip (间隔) 跳过指定的条目选取结果 "skip" => 50

如果你有使用sql(关系)数据库的经验,你也许想查看二者的映射表格 SQL to Mongo Mapping Chart .

聚合(Aggregations)

我们可以使用Mongo提供的方法使用Mongo模型返回聚合结果。聚合结果不是使用MapReduce来计算的。基于此,我们可以非常容易的取得聚合值,比如总计或平均值等:

<?php

$data = Article::aggregate(
    [
        [
            "\$project" => [
                "category" => 1,
            ],
        ],
        [
            "\$group" => [
                "_id" => [
                    "category" => "\$category"
                ],
                "id"  => [
                    "\$max" => "\$_id",
                ],
            ],
        ],
    ]
);
创建和更新记录(Creating Updating/Records)

Phalcon\Mvc\Collection::save() 方法可以用来保存数据,Phalcon会根据当前数据库中的数据来对比以确定是新加一条数据还是更新数据。在Phalcon内部会直接使用 Phalcon\Mvc\Collection 的save或update方法来进行操作。

当然这个方法内部也会调用我们在模型中定义的验证方法或事件等:

<?php

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

if ($robot->save() === false) {
    echo "Umh, We can't store robots right now: \n";

    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo $message, "\n";
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

“_id”属性会被Mongo驱动自动的随MongId_而更新。

<?php

$robot->save();

echo "The generated id is: ", $robot->getId();
验证信息(Validation Messages)

Phalcon\Mvc\Collection 提供了一个信息子系统,使用此系统开发者可以非常容易的实现在数据处理中的验证信息的显示及保存。

每条信息即是一个 Phalcon\Mvc\Model\Message 类的对象实例。我们使用getMessages来取得此信息。每条信息中包含了 如哪个字段产生的消息,或是消息类型等信息:

<?php

if ($robot->save() === false) {
    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo "Message: ", $message->getMessage();
        echo "Field: ", $message->getField();
        echo "Type: ", $message->getType();
    }
}
验证事件和事件管理(Validation Events and Events Manager)

在模型类的数据操作过程中可以产生一些事件。我们可以在这些事件中定义一些业务规则。下面是 Phalcon\Mvc\Collection 所支持的事件及其执行顺序:

操作 名称 能否停止操作 解释
Inserting/Updating beforeValidation YES 在验证和最终插入/更新进行之执行
Inserting beforeValidationOnCreate YES 仅当创建新条目验证之前执行
Updating beforeValidationOnUpdate YES 仅在更新条目验证之前
Inserting/Updating onValidationFails YES (already stopped) 验证执行失败后执行
Inserting afterValidationOnCreate YES 新建条目验证之后执行
Updating afterValidationOnUpdate YES 更新条目后执行
Inserting/Updating afterValidation YES 在验证进行之前执
Inserting/Updating beforeSave YES 在请示的操作(保存)运行之前
Updating beforeUpdate YES 更新操作执行之前运行
Inserting beforeCreate YES 创建操作执行之前运行
Updating afterUpdate NO 更新执行之后执行
Inserting afterCreate NO 创建执行之后
Inserting/Updating afterSave NO 保存执行之后

为了响应一个事件,我们需在模型中实现同名方法:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function beforeValidationOnCreate()
    {
        echo "This is executed before creating a Robot!";
    }
}

在执行操作之前先在指定的事件中设置值有时是非常有用的:

<?php

use Phalcon\Mvc\Collection;

class Products extends Collection
{
    public function beforeCreate()
    {
        // Set the creation date
        $this->created_at = date("Y-m-d H:i:s");
    }

    public function beforeUpdate()
    {
        // Set the modification date
        $this->modified_in = date("Y-m-d H:i:s");
    }
}

另外,这个组件也可以和 Phalcon\Events\Manager 进行集成,这就意味着我们可以通过事件触发创建监听器。

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$eventsManager = new EventsManager();

// Attach an anonymous function as a listener for "model" events
$eventsManager->attach(
    "collection:beforeSave",
    function (Event $event, $robot) {
        if ($robot->name === "Scooby Doo") {
            echo "Scooby Doo isn't a robot!";

            return false;
        }

        return true;
    }
);

$robot = new Robots();

$robot->setEventsManager($eventsManager);

$robot->name = "Scooby Doo";
$robot->year = 1969;

$robot->save();

上面的例子中EventsManager仅在对象和监听器(匿名函数)之间扮演了一个桥接器的角色。如果我们想在创建应用时使用同一个EventsManager,我们需要把这个EventsManager对象设置到 collectionManager服务中:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Collection\Manager as CollectionManager;

// Registering the collectionManager service
$di->set(
    "collectionManager",
    function () {
        $eventsManager = new EventsManager();

        // Attach an anonymous function as a listener for "model" events
        $eventsManager->attach(
            "collection:beforeSave",
            function (Event $event, $model) {
                if (get_class($model) === "Robots") {
                    if ($model->name === "Scooby Doo") {
                        echo "Scooby Doo isn't a robot!";

                        return false;
                    }
                }

                return true;
            }
        );

        // Setting a default EventsManager
        $modelsManager = new CollectionManager();

        $modelsManager->setEventsManager($eventsManager);

        return $modelsManager;
    },
    true
);
实现业务规则(Implementing a Business Rule)

当插入或更新删除等执行时,模型会检查上面表格中列出的方法是否存在。

我们建议定义模型里的验证方法以避免业务逻辑暴露出来。

下面的例子中实现了在保存或更新时对年份的验证,年份不能小于0年:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function beforeSave()
    {
        if ($this->year < 0) {
            echo "Year cannot be smaller than zero!";

            return false;
        }
    }
}

在响应某些事件时返回了false则会停止当前的操作。 如果事实响应未返回任何值, Phalcon\Mvc\Collection 会假定返回了true值。

验证数据完整性(Validating Data Integrity)

Phalcon\Mvc\Collection 提供了若干个事件用于验证数据和实现业务逻辑。特定的事件中我们可以调用内建的验证器, Phalcon提供了一些验证器可以用在此阶段的验证上。

下面的例子中展示了如何使用:

<?php

use Phalcon\Mvc\Collection;
use Phalcon\Mvc\Model\Validator\InclusionIn;
use Phalcon\Mvc\Model\Validator\Numericality;

class Robots extends Collection
{
    public function validation()
    {
        $this->validate(
            new InclusionIn(
                [
                    "field"   => "type",
                    "message" => "Type must be: mechanical or virtual",
                    "domain"  => [
                        "Mechanical",
                        "Virtual",
                    ],
                ]
            )
        );

        $this->validate(
            new Numericality(
                [
                    "field"   => "price",
                    "message" => "Price must be numeric",
                ]
            )
        );

        return $this->validationHasFailed() !== true;
    }
}

上面的例子使用了内建的”InclusionIn”验证器。这个验证器检查了字段的类型是否在指定的范围内。如果值不在范围内即验证失败会返回false. 下面支持的内验证器:

名称 解释
Phalcon\Mvc\Model\Validator\Email 验证email是否正确
Phalcon\Mvc\Model\Validator\Exclusionin 验证值是否不在指定的范围内
Phalcon\Mvc\Model\Validator\Inclusionin 验证值是否在指定的范围内
Phalcon\Mvc\Model\Validator\Numericality 检查字段是否为数字型
Phalcon\Mvc\Model\Validator\Regex 正则检查
Phalcon\Mvc\Model\Validator\StringLength 检查字串长度

除了内建的验证器外,我们还可以创建自己的验证器:

<?php

use Phalcon\Mvc\Model\Validator as CollectionValidator;

class UrlValidator extends CollectionValidator
{
    public function validate($model)
    {
        $field = $this->getOption("field");

        $value = $model->$field;

        $filtered = filter_var($value, FILTER_VALIDATE_URL);

        if (!$filtered) {
            $this->appendMessage(
                "The URL is invalid",
                $field,
                "UrlValidator"
            );

            return false;
        }

        return true;
    }
}

添加验证器到模型:

<?php

use Phalcon\Mvc\Collection;

class Customers extends Collection
{
    public function validation()
    {
        $this->validate(
            new UrlValidator(
                [
                    "field"  => "url",
                ]
            )
        );

        if ($this->validationHasFailed() === true) {
            return false;
        }
    }
}

创建验证器的目的即是使之在多个模型间重复利用以实现代码重用。验证器可简单如下:

<?php

use Phalcon\Mvc\Collection;
use Phalcon\Mvc\Model\Message as ModelMessage;

class Robots extends Collection
{
    public function validation()
    {
        if ($this->type === "Old") {
            $message = new ModelMessage(
                "Sorry, old robots are not allowed anymore",
                "type",
                "MyType"
            );

            $this->appendMessage($message);

            return false;
        }

        return true;
    }
}
删除记录(Deleting Records)

Phalcon\Mvc\Collection::delete() 方法用来删除记录条目。我们可以如下使用:

<?php

$robot = Robots::findFirst();

if ($robot !== false) {
    if ($robot->delete() === false) {
        echo "Sorry, we can't delete the robot right now: \n";

        $messages = $robot->getMessages();

        foreach ($messages as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

也可以使用遍历的方式删除多个条目的数据:

<?php

$robots = Robots::find(
    [
        [
            "type" => "mechanical",
        ]
    ]
);

foreach ($robots as $robot) {
    if ($robot->delete() === false) {
        echo "Sorry, we can't delete the robot right now: \n";

        $messages = $robot->getMessages();

        foreach ($messages as $message) {
            echo $message, "\n";
        }
    } else {
        echo "The robot was deleted successfully!";
    }
}

当删除操作执行时我们可以执行如下事件,以实现定制业务逻辑的目的:

操作 名称 是否可停止 解释
删除 beforeDelete 删除之前执行
删除 afterDelete 删除之后执行
验证失败事件(Validation Failed Events)

验证失败时依据不同的情形下列事件会触发:

操作 名称 解释
插入和或更新 notSave 当插入/更新操作失败时触
插入删除或更新 onValidationFails 当数据操作失败时触发
固有 Id 和 用户主键(Implicit Ids vs. User Primary Keys)

默认 Phalcon\Mvc\Collection 会使用MongoIds_来产生 _id.如果用户想自定义主键也可以只需:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function initialize()
    {
        $this->useImplicitObjectIds(false);
    }
}
设置多个数据库(Setting multiple databases)

Phalcon中,所有的模型可以只属于一个数据库或是多个数据库。事实上当 Phalcon\Mvc\Collection 试图连接数据库时 Phalcon会从DI中取名为mongo的服务。当然我们可在模型的initialize方法中进行连接设置:

<?php

// This service returns a mongo database at 192.168.1.100
$di->set(
    "mongo1",
    function () {
        $mongo = new MongoClient(
            "mongodb://scott:nekhen@192.168.1.100"
        );

        return $mongo->selectDB("management");
    },
    true
);

// This service returns a mongo database at localhost
$di->set(
    "mongo2",
    function () {
        $mongo = new MongoClient(
            "mongodb://localhost"
        );

        return $mongo->selectDB("invoicing");
    },
    true
);

然后在初始化方法,我们定义了模型的连接:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function initialize()
    {
        $this->setConnectionService("mongo1");
    }
}
注入服务到模型(Injecting services into Models)

我们可能需要在模型内使用应用的服务,下面的例子中展示了如何去做:

<?php

use Phalcon\Mvc\Collection;

class Robots extends Collection
{
    public function notSave()
    {
        // Obtain the flash service from the DI container
        $flash = $this->getDI()->getShared("flash");

        $messages = $this->getMessages();

        // Show validation messages
        foreach ($messages as $message) {
            $flash->error(
                (string) $message
            );
        }
    }
}

notSave事件在创建和更新失败时触发。我们使用flash服务来处理验证信息。如此做我们无需在每次保存后打印消息出来。

使用视图(Using Views)

视图代表了应用程序中的用户界面. 视图通常是在 HTML 文件里嵌入 PHP 代码,这些代码仅仅是用来展示数据。 视图的任务是当应用程序发生请求时,提供数据给 web 浏览器或者其他工具。

Phalcon\Mvc\ViewPhalcon\Mvc\View\Simple 负责管理你的MVC应用程序的视图(View)层。

集成视图到控制器(Integrating Views with Controllers)

当某个控制器已经完成了它的周期,Phalcon自动将执行传递到视图组件。视图组件将在视图文件夹中寻找一个文件夹名与最后一个控制器名相同,文件命名与最后一个动作相同的文件执行。例如,如果请求的URL http://127.0.0.1/blog/posts/show/301, Phalcon将如下所示的方式按解析URL:

Server Address 127.0.0.1
Phalcon Directory blog
Controller posts
Action show
Parameter 301

调度程序将寻找一个“PostsController”控制器及其“showAction”动作。对于这个示例的一个简单的控制器文件:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction($postId)
    {
        // Pass the $postId parameter to the view
        $this->view->postId = $postId;
    }
}

setVar允许我们创建视图变量,这样可以在视图模板中使用它们。上面的示例演示了如何传递 $postId 参数到相应的视图模板。

分层渲染(Hierarchical Rendering)

Phalcon\Mvc\View 支持文件的层次结构,在Phalcon中是默认的视图渲染组件。这个层次结构允许通用的布局点(常用的视图)和以控制器命名的文件夹中定义各自的视图模板

该组件使用默认PHP本身作为模板引擎,因此视图应该以.phtml作为拓展名。如果视图目录是 app/views ,视图组件会自动找到这三个视图文件。

名称 文件 解释
Action View app/views/posts/show.phtml 这是该动作相关的视图。它只会在执行 “show” 动作时显示。
Controller Layout app/views/layouts/posts.phtml 这是该控制器相关的视图。它只会 “posts” 控制器内每个动作执行时显示。这个控制器的所有动作将重用这个布局的全部代码。
Main Layout app/views/index.phtml 这是主布局,它将在应用程序的每个控制器或动作执行时显示。

你不需要实现上面提到的所有文件。在文件的层次结构中 Phalcon\Mvc\View 将简单地移动到下一个视图级别。如果这三个视图文件被实现,他们将被按下面方式处理:

<!-- app/views/posts/show.phtml -->

<h3>This is show view!</h3>

<p>I have received the parameter <?php echo $postId; ?></p>
<!-- app/views/layouts/posts.phtml -->

<h2>This is the "posts" controller layout!</h2>

<?php echo $this->getContent(); ?>
<!-- app/views/index.phtml -->
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <h1>This is main layout!</h1>

        <?php echo $this->getContent(); ?>

    </body>
</html>

注意方法 $this->getContent() 被调用的这行。这种方法指示 Phalcon\Mvc\View 在这里注入前面视图层次结构执行的内容。在上面的示例中,输出将会是:

_images/views-1.png

请求生成的HTML的将为:

<!-- app/views/index.phtml -->
<html>
    <head>
        <title>Example</title>
    </head>
    <body>

        <h1>This is main layout!</h1>

        <!-- app/views/layouts/posts.phtml -->

        <h2>This is the "posts" controller layout!</h2>

        <!-- app/views/posts/show.phtml -->

        <h3>This is show view!</h3>

        <p>I have received the parameter 101</p>

    </body>
</html>
使用模版(Using Templates)

模板视图可以用来分享共同的视图代码。他们作为控制器的布局,所以你需要放在布局目录。

模板视图可以在布局之前渲染(使用 $this->view->setTemplateBefore() 方法) ,也可以布局之后渲染(使用 this->view->setTemplateAfter() 方法)。 下面的例子中,模板视图(layouts/common.phtml)是在布局(layouts/posts.phtml)之后渲染的:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function initialize()
    {
        $this->view->setTemplateAfter("common");
    }

    public function lastAction()
    {
        $this->flash->notice(
            "These are the latest posts"
        );
    }
}
<!-- app/views/index.phtml -->
<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>
        <?php echo $this->getContent(); ?>
    </body>
</html>
<!-- app/views/layouts/common.phtml -->

<ul class="menu">
    <li><a href="/">Home</a></li>
    <li><a href="/articles">Articles</a></li>
    <li><a href="/contact">Contact us</a></li>
</ul>

<div class="content"><?php echo $this->getContent(); ?></div>
<!-- app/views/layouts/posts.phtml -->

<h1>Blog Title</h1>

<?php echo $this->getContent(); ?>
<!-- app/views/posts/last.phtml -->

<article>
    <h2>This is a title</h2>
    <p>This is the post content</p>
</article>

<article>
    <h2>This is another title</h2>
    <p>This is another post content</p>
</article>

最终的输出如下:

<!-- app/views/index.phtml -->
<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>

        <!-- app/views/layouts/common.phtml -->

        <ul class="menu">
            <li><a href="/">Home</a></li>
            <li><a href="/articles">Articles</a></li>
            <li><a href="/contact">Contact us</a></li>
        </ul>

        <div class="content">

            <!-- app/views/layouts/posts.phtml -->

            <h1>Blog Title</h1>

            <!-- app/views/posts/last.phtml -->

            <article>
                <h2>This is a title</h2>
                <p>This is the post content</p>
            </article>

            <article>
                <h2>This is another title</h2>
                <p>This is another post content</p>
            </article>

        </div>

    </body>
</html>

如果我们调用 $this->view->setTemplateBefore("common") 方法, 最终输出如下:

<!-- app/views/index.phtml -->
<!DOCTYPE html>
<html>
    <head>
        <title>Blog's title</title>
    </head>
    <body>

        <!-- app/views/layouts/posts.phtml -->

        <h1>Blog Title</h1>

        <!-- app/views/layouts/common.phtml -->

        <ul class="menu">
            <li><a href="/">Home</a></li>
            <li><a href="/articles">Articles</a></li>
            <li><a href="/contact">Contact us</a></li>
        </ul>

        <div class="content">

            <!-- app/views/posts/last.phtml -->

            <article>
                <h2>This is a title</h2>
                <p>This is the post content</p>
            </article>

            <article>
                <h2>This is another title</h2>
                <p>This is another post content</p>
            </article>

        </div>

    </body>
</html>
渲染级别控制(Control Rendering Levels)

如上所述,Phalcon\Mvc\View 支持视图分层。你可能需要控制视图组件的渲染级别。方法 Phalcon\Mvc\View::setRenderLevel() 提供这个功能。

这种方法可以从控制器调用或是从上级视图层干涉渲染过程。

<?php

use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function findAction()
    {
        // This is an Ajax response so it doesn't generate any kind of view
        $this->view->setRenderLevel(
            View::LEVEL_NO_RENDER
        );

        // ...
    }

    public function showAction($postId)
    {
        // Shows only the view related to the action
        $this->view->setRenderLevel(
            View::LEVEL_ACTION_VIEW
        );
    }
}

可用的渲染级别:

类常量 解释 顺 序
LEVEL_NO_RENDER 表明要避免产生任何形式的显示。  
LEVEL_ACTION_VIEW 生成显示到视图关联的动作。 1
LEVEL_BEFORE_TEMPLATE 生成显示到控制器模板布局之前。 2
LEVEL_LAYOUT 生成显示到控制器布局。 3
LEVEL_AFTER_TEMPLATE 生成显示到控制器模板布局后。 4
LEVEL_MAIN_LAYOUT 生成显示到主布局。文件: views/index.phtml 5
关闭渲染级别(Disabling render levels)

你可以永久或暂时禁用渲染级别。如果不在整个应用程序使用,可以永久禁用一个级别:

<?php

use Phalcon\Mvc\View;

$di->set(
    "view",
    function () {
        $view = new View();

        // Disable several levels
        $view->disableLevel(
            [
                View::LEVEL_LAYOUT      => true,
                View::LEVEL_MAIN_LAYOUT => true,
            ]
        );

        return $view;
    },
    true
);

或者在某些应用程序的一部分暂时或禁用:

<?php

use Phalcon\Mvc\View;
use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function findAction()
    {
        $this->view->disableLevel(
            View::LEVEL_MAIN_LAYOUT
        );
    }
}
选择视图(Picking Views)

如上所述, 当 Phalcon\Mvc\ViewPhalcon\Mvc\Application 视图渲染的是最后的一个相关的控制器和执行动作。你可以使用 Phalcon\Mvc\View::pick() 方法覆盖它。

<?php

use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function listAction()
    {
        // Pick "views-dir/products/search" as view to render
        $this->view->pick("products/search");

        // Pick "views-dir/books/list" as view to render
        $this->view->pick(
            [
                "books",
            ]
        );

        // Pick "views-dir/products/search" as view to render
        $this->view->pick(
            [
                1 => "search",
            ]
        );
    }
}
关闭视图(Disabling the view)

如果你的控制器不在视图里产生(或没有)任何输出,你可以禁用视图组件来避免不必要的处理:

<?php

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function closeSessionAction()
    {
        // Close session
        // ...

        // Disable the view to avoid rendering
        $this->view->disable();
    }
}

Alternatively, you can return false to produce the same effect:

<?php

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function closeSessionAction()
    {
        // ...

        // Disable the view to avoid rendering
        return false;
    }
}

你可以返回一个“response”的对象,避免手动禁用视图:

<?php

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function closeSessionAction()
    {
        // Close session
        // ...

        // A HTTP Redirect
        return $this->response->redirect("index/index");
    }
}
简单渲染(Simple Rendering)

Phalcon\Mvc\View\SimplePhalcon\Mvc\View 的另一个组成部分。 它保留 Phalcon\Mvc\View 的大多数的设计思想,但缺少文件的层次结构是它们的主要区别。

该组件允许开发人员控制渲染视图时,视图所在位置。 此外,该组件可以利用从视图中继承的可用的模板引擎。比如 Volt 和其他的一些模板引擎。

默认使用该组件必须替换服务容器:

<?php

use Phalcon\Mvc\View\Simple as SimpleView;

$di->set(
    "view",
    function () {
        $view = new SimpleView();

        $view->setViewsDir("../app/views/");

        return $view;
    },
    true
);

自动渲染必须在 Phalcon\Mvc\Application 被禁用 (如果需要):

<?php

use Exception;
use Phalcon\Mvc\Application;

try {
    $application = new Application($di);

    $application->useImplicitView(false);

    $response = $application->handle();

    $response->send();
} catch (Exception $e) {
    echo $e->getMessage();
}

渲染一个视图必须显式地调用render方法来指定你想显示的视图的相对路径:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends \Controller
{
    public function indexAction()
    {
        // Render 'views-dir/index.phtml'
        echo $this->view->render("index");

        // Render 'views-dir/posts/show.phtml'
        echo $this->view->render("posts/show");

        // Render 'views-dir/index.phtml' passing variables
        echo $this->view->render(
            "index",
            [
                "posts" => Posts::find(),
            ]
        );

        // Render 'views-dir/posts/show.phtml' passing variables
        echo $this->view->render(
            "posts/show",
            [
                "posts" => Posts::find(),
            ]
        );
    }
}

This is different to Phalcon\Mvc\View who’s render() method uses controllers and actions as parameters:

<?php

$params = [
    "posts" => Posts::find(),
];

// Phalcon\Mvc\View
$view = new \Phalcon\Mvc\View();
echo $view->render("posts", "show", $params);

// Phalcon\Mvc\View\Simple
$simpleView = new \Phalcon\Mvc\View\Simple();
echo $simpleView->render("posts/show", $params);
使用局部模版(Using Partials)

局部模板是把渲染过程分解成更简单、更好管理的、可以重用不同部分的应用程序块的另一种方式。你可以移动渲染特定响应的代码块到自己的文件。

使用局部模板的一种方法是把它们作为相等的子例程:作为一种移动细节视图,这样您的代码可以更容易地被理解。例如,您可能有一个视图看起来像这样:

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

方法 partial() 也接受一个只存在于局部范围的变量/参数的数组作为第二个参数:

<?php $this->partial("shared/ad_banner", ["id" => $site->id, "size" => "big"]); ?>
控制器传值给视图(Transfer values from the controller to views)

Phalcon\Mvc\View 可以在每个控制器中使用视图变量 ($this->view)。 你可以在控制器动作中使用视图对象的 setVar() 方法直接设置视图变量。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction()
    {
        $user  = Users::findFirst();
        $posts = $user->getPosts();

        // Pass all the username and the posts to the views
        $this->view->setVar("username", $user->username);
        $this->view->setVar("posts",    $posts;

        // Using the magic setter
        $this->view->username = $user->username;
        $this->view->posts    = $posts;

        // Passing more than one variable at the same time
        $this->view->setVars(
            [
                "username" => $user->username,
                "posts"    => $posts,
            ]
        );
    }
}

名为:code:`setVar()`的第一参数值的变量将在视图中创建的,并且可以被使用。变量可以是任何类型:从一个简单的字符串,整数等等,变为更复杂的结构,如数组,集合。

<h1>
    {{ username }}'s Posts
</h1>

<div class="post">
<?php

    foreach ($posts as $post) {
        echo "<h2>", $post->title, "</h2>";
    }

?>
</div>
缓存视图片段(Caching View Fragments)

有时当你开发动态网站和一些区域不会经常更新,请求的输出是完全相同的。 Phalcon\Mvc\View 提供缓存全部或部分的渲染输出来提高性能。

Phalcon\Mvc\View 配合 Phalcon\Cache 能提供一种更简单的方法缓存输出片段。你可以手动设置缓存处理程序或一个全局处理程序。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function showAction()
    {
        // Cache the view using the default settings
        $this->view->cache(true);
    }

    public function showArticleAction()
    {
        // Cache this view for 1 hour
        $this->view->cache(
            [
                "lifetime" => 3600,
            ]
        );
    }

    public function resumeAction()
    {
        // Cache this view for 1 day with the key "resume-cache"
        $this->view->cache(
            [
                "lifetime" => 86400,
                "key"      => "resume-cache",
            ]
        );
    }

    public function downloadAction()
    {
        // Passing a custom service
        $this->view->cache(
            [
                "service"  => "myCache",
                "lifetime" => 86400,
                "key"      => "resume-cache",
            ]
        );
    }
}

如果我们没有定义缓存的key, 这个组件会自动创建一个 MD5 散列值(由当前控制器名和视图名组成”controller/view”的格式)作为key。 为每个action定义一个单独的缓存key,这是一个好的习惯与规范,这样你可以很容易地识别与每个视图相关联的缓存。

当视图组件需要缓存一些数据时,它会从服务容器(DI)中请求缓存服务。 这个服务的名称约定为”viewCache”:

<?php

use Phalcon\Cache\Frontend\Output as OutputFrontend;
use Phalcon\Cache\Backend\Memcache as MemcacheBackend;

// Set the views cache service
$di->set(
    "viewCache",
    function () {
        // Cache data for one day by default
        $frontCache = new OutputFrontend(
            [
                "lifetime" => 86400,
            ]
        );

        // Memcached connection settings
        $cache = new MemcacheBackend(
            $frontCache,
            [
                "host" => "localhost",
                "port" => "11211",
            ]
        );

        return $cache;
    }
);
前端 Phalcon\Cache\Frontend\Output 和服务 ‘viewCache’ 必须在服务容器(DI)注册为 总是开放的(不共享 not shared)

在视图中使用视图缓存也是有用的,以防止控制器执行过程所产生的数据被显示。

为了实现这一点,我们必须确定每个缓存键是独一无二的。 首先,我们验证缓存不存在或是否过期,再去计算/查询并在视图中显示数据:

<?php

use Phalcon\Mvc\Controller;

class DownloadController extends Controller
{
    public function indexAction()
    {
        // Check whether the cache with key "downloads" exists or has expired
        if ($this->view->getCache()->exists("downloads")) {
            // Query the latest downloads
            $latest = Downloads::find(
                [
                    "order" => "created_at DESC",
                ]
            );

            $this->view->latest = $latest;
        }

        // Enable the cache with the same key "downloads"
        $this->view->cache(
            [
                "key" => "downloads",
            ]
        );
    }
}

PHP alternative site 是实现缓存片段的一个例子。

模版引擎(Template Engines)

模板引擎可以帮助设计者不使用复杂的语法创建视图。Phalcon包含一个强大的和快速的模板引擎,它被叫做叫 Volt

此外, Phalcon\Mvc\View 允许你使用其它的模板引擎而不是简单的PHP或者Volt。

使用不同的模板引擎,通常需要使用外部PHP库并且引入复杂的文本解析来为用户生成最终的输出解析。这通常会增加一些你的应用程序的资源耗费。

如果一个外部模板引擎被使用,Phalcon\Mvc\View 提供完全相同的视图渲染等级,仍然可以尝试在这些模板内访问的更多的API。

该组件使用的适配器,这些适配器帮助 Phalcon 与外部模板引擎以一个统一的方式对话,让我们看看如何整合。

创建模版引擎(Creating your own Template Engine Adapter)

有很多模板引擎,你可能想整合或建立一个自己的。开始使用一个外部的模板引擎的第一步是创建一个适配器。

模板引擎的适配器是一个类,作为 Phalcon\Mvc\View 和模板引擎本身之间的桥梁。 通常它只需要实现两个方法: __construct() and render()。首先接收 Phalcon\Mvc\View 和应用程序使用的DI容器来创建引擎适配器实例。

方法 render() 接受一个到视图文件的绝对路径和视图参数,设置使用 $this->view->setVar()。必要的时候,你可以读入或引入它。

<?php

use Phalcon\DiInterface;
use Phalcon\Mvc\Engine;

class MyTemplateAdapter extends Engine
{
    /**
     * Adapter constructor
     *
     * @param \Phalcon\Mvc\View $view
     * @param \Phalcon\Di $di
     */
    public function __construct($view, DiInterface $di)
    {
        // Initialize here the adapter
        parent::__construct($view, $di);
    }

    /**
     * Renders a view using the template engine
     *
     * @param string $path
     * @param array $params
     */
    public function render($path, $params)
    {
        // Access view
        $view = $this->_view;

        // Access options
        $options = $this->_options;

        // Render the view
        // ...
    }
}
替换模版引擎(Changing the Template Engine)

你可以完全更换模板引擎或同时使用多个模板引擎。方法 Phalcon\Mvc\View::registerEngines() 接受一个包含定义模板引擎数据的数组。每个引擎的键名是一个区别于其他引擎的拓展名。模板文件和特定的引擎关联必须有这些扩展名。

Phalcon\Mvc\View::registerEngines() 会按照相关顺序定义模板引擎执行。如果 Phalcon\Mvc\View 发现具有相同名称但不同的扩展,它只会使第一个。

如果你想在应用程序的每个请求中注册一个或一组模板引擎。你可以在创建视图时注册服务:

<?php

use Phalcon\Mvc\View;

// Setting up the view component
$di->set(
    "view",
    function () {
        $view = new View();

        // A trailing directory separator is required
        $view->setViewsDir("../app/views/");

        // Set the engine
        $view->registerEngines(
            [
                ".my-html" => "MyTemplateAdapter",
            ]
        );

        // Using more than one template engine
        $view->registerEngines(
            [
                ".my-html" => "MyTemplateAdapter",
                ".phtml"   => "Phalcon\\Mvc\\View\\Engine\\Php",
            ]
        );

        return $view;
    },
    true
);

Phalcon Incubator 有一些适配器可用于数个模板引擎

注入服务到视图(Injecting services in View)

每个视图执行内部包含一个 Phalcon\Di\Injectable 实例, 提供方便地方式访问应用程序的服务容器。

下面的示例演示如何用一个框架约定好的URL服务写一个 jQuery ajax request 。 “url” (usually Phalcon\Mvc\Url) 服务被注入在视图由相同名称的属性访问:

<script type="text/javascript">

$.ajax({
    url: "<?php echo $this->url->get("cities/get"); ?>"
})
.done(function () {
    alert("Done!");
});

</script>
独立的组件(Stand-Alone Component)

在Phalcon的所有部件都可以作为胶水(glue) 组件单独使用,因为它们彼此松散耦合:

分层渲染(Hierarchical Rendering)

如下所示,可以单独使用 Phalcon\Mvc\View

<?php

use Phalcon\Mvc\View;

$view = new View();

// A trailing directory separator is required
$view->setViewsDir("../app/views/");

// Passing variables to the views, these will be created as local variables
$view->setVar("someProducts",       $products);
$view->setVar("someFeatureEnabled", true);

// Start the output buffering
$view->start();

// Render all the view hierarchy related to the view products/list.phtml
$view->render("products", "list");

// Finish the output buffering
$view->finish();

echo $view->getContent();

使用短的语法也可以:

<?php

use Phalcon\Mvc\View;

$view = new View();

echo $view->getRender(
    "products",
    "list",
    [
        "someProducts"       => $products,
        "someFeatureEnabled" => true,
    ],
    function ($view) {
        // Set any extra options here

        $view->setViewsDir("../app/views/");

        $view->setRenderLevel(
            View::LEVEL_LAYOUT
        );
    }
);
简单渲染(Simple Rendering)

如下所示,以单独使用 Phalcon\Mvc\View\Simple

<?php

use Phalcon\Mvc\View\Simple as SimpleView;

$view = new SimpleView();

// A trailing directory separator is required
$view->setViewsDir("../app/views/");

// Render a view and return its contents as a string
echo $view->render("templates/welcomeMail");

// Render a view passing parameters
echo $view->render(
    "templates/welcomeMail",
    [
        "email"   => $email,
        "content" => $content,
    ]
);
视图事件(View Events)

如果事件管理器(EventsManager)存在,Phalcon\Mvc\ViewPhalcon\Mvc\View 能够发送事件到 EventsManager。事件触发使用的“view”类型。当返回布尔值false,一些事件可以停止运行。以下是被支持的事件:

事件名称 触发点 是否可以停止?
beforeRender 渲染过程开始前触发 Yes
beforeRenderView 渲染一个现有的视图之前触发 Yes
afterRenderView 渲染一个现有的视图之后触发 No
afterRender 渲染过程完成后触发 No
notFoundView 视图不存在时触发 No

下面的例子演示了如何将监听器附加到该组件:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\View;

$di->set(
    "view",
    function () {
        // Create an events manager
        $eventsManager = new EventsManager();

        // Attach a listener for type "view"
        $eventsManager->attach(
            "view",
            function (Event $event, $view) {
                echo $event->getType(), " - ", $view->getActiveRenderPath(), PHP_EOL;
            }
        );

        $view = new View();

        $view->setViewsDir("../app/views/");

        // Bind the eventsManager to the view component
        $view->setEventsManager($eventsManager);

        return $view;
    },
    true
);

下面的示例演示如何创建一个插件 Tidy ,清理/修复的渲染过程中产生的HTML:

<?php

use Phalcon\Events\Event;

class TidyPlugin
{
    public function afterRender(Event $event, $view)
    {
        $tidyConfig = [
            "clean"          => true,
            "output-xhtml"   => true,
            "show-body-only" => true,
            "wrap"           => 0,
        ];

        $tidy = tidy_parse_string(
            $view->getContent(),
            $tidyConfig,
            "UTF8"
        );

        $tidy->cleanRepair();

        $view->setContent(
            (string) $tidy
        );
    }
}

// Attach the plugin as a listener
$eventsManager->attach(
    "view:afterRender",
    new TidyPlugin()
);

视图助手 (Tags)(View Helpers (Tags))

因为HTML标签的命名方式和很多标签属性,让书写HTML标签变成一项超级沉闷的工作。Phalcon提供 Phalcon\Tag 类来处理这些复杂而无趣的事情。

这个简单的指导不是一个完整的关于视图助手的文档,请查看 Phalcon\Tag 以获得视图助手的完整说明。
文档类型(Document Type of Content)

Phalcon 提供 Phalcon\Tag::setDoctype() 方法可以设置输出内容的文档类型。此类型设置可能被其他的tag方法影响。

常量 对应的文档类型
HTML32 HTML 3.2
HTML401_STRICT HTML 4.01 严格模式
HTML401_TRANSITIONAL HTML 4.01 过渡模式
HTML401_FRAMESET HTML 4.01 Frameset
HTML5 HTML 5
XHTML10_STRICT XHTML 1.0 严格模式
XHTML10_TRANSITIONAL XHTML 1.0 过渡模式
XHTML10_FRAMESET XHTML 1.0 Frameset
XHTML11 XHTML 1.1
XHTML20 XHTML 2.0
XHTML5 XHTML 5

设置文档类型:

<?php

use Phalcon\Tag;

$this->tag->setDoctype(Tag::HTML401_STRICT);

?>

获取文档类型:

<?= $this->tag->getDoctype() ?>
<html>
<!-- your HTML code -->
</html>

如下的html代码将被生成:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<!-- your HTML code -->
</html>

Volt 语法:

{{ get_doctype() }}
<html>
<!-- your HTML code -->
</html>
创建表单(Creating Forms)

在Web应用中,表单是获取用户输入的重要工具,下面的例子显示了使用视图助手(tag)如何去生成一个简单的form表单。

<!-- Sending the form by method POST -->
<?= $this->tag->form("products/search") ?>
    <label for="q">Search:</label>

    <?= $this->tag->textField("q") ?>

    <?= $this->tag->submitButton("Search") ?>
<?= $this->tag->endForm() ?>

<!-- Specifying another method or attributes for the FORM tag -->
<?= $this->tag->form(["products/search", "method" => "get"]); ?>
    <label for="q">Search:</label>

    <?= $this->tag->textField("q"); ?>

    <?= $this->tag->submitButton("Search"); ?>
<?= $this->tag->endForm() ?>

以上代码会生成如下的html:

<form action="/store/products/search/" method="get">
    <label for="q">Search:</label>

    <input type="text" id="q" value="" name="q" />

    <input type="submit" value="Search" />
</form>

使用Volt生成表单:

<!-- Specifying another method or attributes for the FORM tag -->
{{ form("products/search", "method": "get") }}
    <label for="q">Search:</label>

    {{ text_field("q") }}

    {{ submit_button("Search") }}
{{ endForm() }}

Phalcon也提供了 form builder 类去以面向对象的风格去生成这样的表单。

使用助手生成表单控件(Helpers to Generate Form Elements)

Phalcon 提供了一系列的方法去生成例如文本域(text),按钮(button)和其他的一些form表单元素。提供给所有方法(helper)的第一个参数都是需要创建的表单元素的名称(name属性)。当提交表单的时候,这个名称将被和form表单数据一起传输。在控制器中,你可以使用request对象 ($this->request) 的 getPost()getQuery() 方法结合之前定义的名字(name属性)来获取到这些值。

<?php echo $this->tag->textField("username") ?>

<?php echo $this->tag->textArea(
    [
        "comment",
        "This is the content of the text-area",
        "cols" => "6",
        "rows" => 20,
    ]
) ?>

<?php echo $this->tag->passwordField(
    [
        "password",
        "size" => 30,
    ]
) ?>

<?php echo $this->tag->hiddenField(
    [
        "parent_id",
        "value" => "5",
    ]
) ?>

Volt 的语法:

{{ text_field("username") }}

{{ text_area("comment", "This is the content", "cols": "6", "rows": 20) }}

{{ password_field("password", "size": 30) }}

{{ hidden_field("parent_id", "value": "5") }}
使用选择框(Making Select Boxes)

生成选择框(select)很简单,特别是当你已经把相关的数据存储在了PHP的关联数组中。生成select的方法是 Phalcon\Tag::select()Phalcon\Tag::selectStatic() 。方法 Phalcon\Tag::select()Phalcon\Mvc\Model 一起使用会更好。当然 Phalcon\Tag::selectStatic() 也可以和PHP的数组一起工作。

<?php

$products = Products::find("type = 'vegetables'");

// Using data from a resultset
echo $this->tag->select(
    [
        "productId",
        $products,
        "using" => [
            "id",
            "name",
        ]
    ]
);

// Using data from an array
echo $this->tag->selectStatic(
    [
        "status",
        [
            "A" => "Active",
            "I" => "Inactive",
        ]
    ]
);

以下HTML代码将会被生成:

<select id="productId" name="productId">
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

<select id="status" name="status">
    <option value="A">Active</option>
    <option value="I">Inactive</option>
</select>

你可以添加一个空的选项(option)到被生成的HTML页面中:

<?php

$products = Products::find("type = 'vegetables'");

// Creating a Select Tag with an empty option
echo $this->tag->select(
    [
        "productId",
        $products,
        "using"    => [
            "id",
            "name",
        ],
        "useEmpty" => true,
    ]
);

生成的HTML如下:

<select id="productId" name="productId">
    <option value="">Choose..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>
<?php

$products = Products::find("type = 'vegetables'");

// Creating a Select Tag with an empty option with default text
echo $this->tag->select(
    [
        "productId",
        $products,
        "using"      => [
            "id",
            "name",
        ],
        "useEmpty"   => true,
        "emptyText"  => "Please, choose one...",
        "emptyValue" => "@",
    ]
);
<select id="productId" name="productId">
    <option value="@">Please, choose one..</option>
    <option value="101">Tomato</option>
    <option value="102">Lettuce</option>
    <option value="103">Beans</option>
</select>

以Volt的语法生成以上的select选择框

{# Creating a Select Tag with an empty option with default text #}
{{ select('productId', products, 'using': ['id', 'name'],
    'useEmpty': true, 'emptyText': 'Please, choose one...', 'emptyValue': '@') }}
设置 HTML 属性(Assigning HTML attributes)

所有的方法的第一个参数可以是一个数组,这个数组包含了这个被生成的HTML元素额外的属性。

<?php $this->tag->textField(
    [
        "price",
        "size"        => 20,
        "maxlength"   => 30,
        "placeholder" => "Enter a price",
    ]
) ?>

Volt语法:

{{ text_field("price", "size": 20, "maxlength": 30, "placeholder": "Enter a price") }}

以下的HTML代码将被生成。

<input type="text" name="price" id="price" size="20" maxlength="30"
    placeholder="Enter a price" />
设置助手的值(Setting Helper Values)
通过控制器(From Controllers)

使用MVC框架编程时的一个好习惯是给form元素在视图中设定一个明确的值。你可以直接使用 Phalcon\Tag::setDefault() 在控制器中设置这个值。这个方法为所有的视图助手的方法预先设定了一个值,如果任意一个视图助手方法有一个和此预设值相匹配的名字,这个值将会被使用,除非那个视图方法明确的指定了这个值。

<?php

use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function indexAction()
    {
        $this->tag->setDefault("color", "Blue");
    }
}

例如,在视图中一个选择框助手方法(select helper)匹配到了这个之前被预设的值”color”

<?php

echo $this->tag->selectStatic(
    [
        "color",
        [
            "Yellow" => "Yellow",
            "Blue"   => "Blue",
            "Red"    => "Red",
        ]
    ]
);

当这个选择框被生成的时候,”Blue”将被默认选中。

<select id="color" name="color">
    <option value="Yellow">Yellow</option>
    <option value="Blue" selected="selected">Blue</option>
    <option value="Red">Red</option>
</select>
通过请求(From the Request)
Phalcon\Tag 助手有一个特性,它可以在用户请求的时候保持表单的值。这个特性让你在不损失任何输入数据的情况下显示一些确认信息。
直接设置值(Specifying values directly)

所有的表单方法都支持参数”value”。你可以直接设置一个明确的值给表单方法。当这个值被明确设定的时候,任何通过 setDefault() 或者通过 请求(request) 所设置的值将被直接忽略。

动态设置文档标题(Changing dynamically the Document Title)

Phalcon\Tag 类提供了一些方法,让我们可以在控制器中动态地设置HTML文档的标题(title)。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function initialize()
    {
        $this->tag->setTitle("Your Website");
    }

    public function indexAction()
    {
        $this->tag->prependTitle("Index of Posts - ");
    }
}
<html>
    <head>
        <?php echo $this->tag->getTitle(); ?>
    </head>

    <body>

    </body>
</html>

以下的HTML代码将会被生成:

<html>
    <head>
        <title>Index of Posts - Your Website</title>
    </head>

    <body>

    </body>
</html>
静态内容助手(Static Content Helpers)

Phalcon\Tag 也提供一些其他的方法去生成一些其他的标签,例如脚本(script),超链接(link)或者图片(img)。它可以帮助你很快的生成一些你应用中的静态资源

图片(Images)
<?php

// Generate <img src="/your-app/img/hello.gif">
echo $this->tag->image("img/hello.gif");

// Generate <img alt="alternative text" src="/your-app/img/hello.gif">
echo $this->tag->image(
    [
       "img/hello.gif",
       "alt" => "alternative text",
    ]
);

Volt 语法:

{# Generate <img src="/your-app/img/hello.gif"> #}
{{ image("img/hello.gif") }}

{# Generate <img alt="alternative text" src="/your-app/img/hello.gif"> #}
{{ image("img/hello.gif", "alt": "alternative text") }}
样式表(Stylesheets)
<?php

// Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css">
echo $this->tag->stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);

// Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css">
echo $this->tag->stylesheetLink("css/styles.css");

Volt 语法:

{# Generate <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rosario" type="text/css"> #}
{{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }}

{# Generate <link rel="stylesheet" href="/your-app/css/styles.css" type="text/css"> #}
{{ stylesheet_link("css/styles.css") }}
脚本(Javascript)
<?php

// Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script>
echo $this->tag->javascriptInclude("http://localhost/javascript/jquery.min.js", false);

// Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script>
echo $this->tag->javascriptInclude("javascript/jquery.min.js");

Volt 语法:

{# Generate <script src="http://localhost/javascript/jquery.min.js" type="text/javascript"></script> #}
{{ javascript_include("http://localhost/javascript/jquery.min.js", false) }}

{# Generate <script src="/your-app/javascript/jquery.min.js" type="text/javascript"></script> #}
{{ javascript_include("javascript/jquery.min.js") }}
HTML5 对象(HTML5 elements - generic HTML helper)

Phalcon 提供了一个通用的方法去生成任何HTML的元素。在这个方法中,需要开发者将有效的HTML元素标签传给此方法。

<?php

// Generate
// <canvas id="canvas1" width="300" class="cnvclass">
// This is my canvas
// </canvas>
echo $this->tag->tagHtml("canvas", ["id" => "canvas1", "width" => "300", "class" => "cnvclass"], false, true, true);
echo "This is my canvas";
echo $this->tag->tagHtmlClose("canvas");

Volt 语法:

{# Generate
<canvas id="canvas1" width="300" class="cnvclass">
This is my canvas
</canvas> #}
{{ tag_html("canvas", ["id": "canvas1", width": "300", "class": "cnvclass"], false, true, true) }}
    This is my canvas
{{ tag_html_close("canvas") }}
标签服务(Tag Service)

Phalcon\Tag 类可以通过 ‘tag’ 服务来使用,这意味着你可以在服务容器被加载的任何地方访问到它。

<?php echo $this->tag->linkTo("pages/about", "About") ?>

在服务容器中我们可以很容易的添加一个新的组件去替换’tag’组件。

<?php

use Phalcon\Tag;

class MyTags extends Tag
{
    // ...

    // Create a new helper
    public static function myAmazingHelper($parameters)
    {
        // ...
    }

    // Override an existing method
    public static function textField($parameters)
    {
        // ...
    }
}

然后改变’tag’标签的定义:

<?php

$di["tag"] = function () {
    return new MyTags();
};
创建助手(Creating your own helpers)

你可以简单地创建你自己的方法。首先,在你的控制器和模型的同级目录下创建一个新的文件夹,给此文件夹起一个和它功能相关的名字。在这里,叫它”customhelpers”好了。接下来我们在此文件夹下创建一个新的文件命名为 MyTags.php 这时,我们有一个类似于 /app/customhelpers/MyTags.php 的结构,我们将扩展(extend) Phalcon\Tag 并且实现(implement)这个类。下面是一个自定义的助手(helper)类:

<?php

use Phalcon\Tag;

class MyTags extends Tag
{
    /**
     * Generates a widget to show a HTML5 audio tag
     *
     * @param array
     * @return string
     */
    public static function audioField($parameters)
    {
        // Converting parameters to array if it is not
        if (!is_array($parameters)) {
            $parameters = [$parameters];
        }

        // Determining attributes "id" and "name"
        if (!isset($parameters[0])) {
            $parameters[0] = $parameters["id"];
        }

        $id = $parameters[0];

        if (!isset($parameters["name"])) {
            $parameters["name"] = $id;
        } else {
            if (!$parameters["name"]) {
                $parameters["name"] = $id;
            }
        }

        // Determining widget value,
        // \Phalcon\Tag::setDefault() allows to set the widget value
        if (isset($parameters["value"])) {
            $value = $parameters["value"];

            unset($parameters["value"]);
        } else {
            $value = self::getValue($id);
        }

        // Generate the tag code
        $code = '<audio id="' . $id . '" value="' . $value . '" ';

        foreach ($parameters as $key => $attributeValue) {
            if (!is_integer($key)) {
                $code.= $key . '="' . $attributeValue . '" ';
            }
        }

        $code.=" />";

        return $code;
    }
}

在我们创建了自定义的助手(helper)类之后,我们要在我们的public目录下的”index.php”中自动加载那个包含我们自定义助手类的目录。

<?php

use Phalcon\Loader;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault();
use Phalcon\Exception as PhalconException;

try {
    $loader = new Loader();

    $loader->registerDirs(
        [
            "../app/controllers",
            "../app/models",
            "../app/customhelpers", // Add the new helpers folder
        ]
    );

    $loader->register();

    $di = new FactoryDefault();

    // Assign our new tag a definition so we can call it
    $di->set(
        "MyTags",
        function () {
            return new MyTags();
        }
    );

    $application = new Application($di);

    $response = $application->handle();

    $response->send();
} catch (PhalconException $e) {
    echo "PhalconException: ", $e->getMessage();
}

现在,你就可以在你的视图中使用你的新助手类了。

<body>

    <?php

    echo MyTags::audioField(
        [
            "name" => "test",
            "id"   => "audio_test",
            "src"  => "/path/to/audio.mp3",
        ]
    );

    ?>

</body>

在下一节中,我们将讨论关于 Volt 的内容,它是PHP的一个速度很快的模板引擎,在 Phalcon\Tag 中你将得到更多关于视图助手的友好的提示。

资源文件管理(Assets Management)

Phalcon\Assets 是一个让开发者管理静态资源的组件,如管理CSS,JavaScript等。

Phalcon\Assets\Manager 存在于DI容器中,所以我们可以在服务容器存在的 任何地方使用它来添加/管理资源。

添加资源(Adding Resources)

Assets支持两个内置的资源管理器:css和javascripts.我们可以根据需要创建其它的资源。资源管理器内部保存了两类资源集合一为 JavaScript另一为CSS.

我们可以非常简单的向这两个集合里添加资源,如下:

<?php

use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    public function index()
    {
        // 添加本地CSS资源
        $this->assets->addCss("css/style.css");
        $this->assets->addCss("css/index.css");

        // 添加本地JavaScript资源
        $this->assets->addJs("js/jquery.js");
        $this->assets->addJs("js/bootstrap.min.js");
    }
}

然后我们可以在视图中输出资源:

<html>
    <head>
        <title>Some amazing website</title>

        <?php $this->assets->outputCss(); ?>
    </head>

    <body>
        <!-- ... -->

        <?php $this->assets->outputJs(); ?>
    </body>
<html>

Volt语法:

<html>
    <head>
        <title>Some amazing website</title>

        {{ assets.outputCss() }}
    </head>

    <body>
        <!-- ... -->

        {{ assets.outputJs() }}
    </body>
<html>

为了提升页面加载性能,建议在页面底部(</body>标签前)加载javascript,而不是在 <head> 处加载。

本地与远程资源(Local/Remote resources)

本地资源是同一应用中的资源,这些资源存在于应用的根目录中。 Phalcon\Mvc\Url 用来生成 本地的url.

远程资源即是一种存在于CDN或其它远程服务器上的资源,比如常用的jQuery, Bootstrap等资源。

addCss()addJs() 方法的第二个参数的作用是申明当前资源是本地资源还是远程资源(true 为本地资源, false 为远程资源)。 不传此参数时,默认为本地资源:

<?php

public function indexAction()
{
    // 添加远程及本地资源
    $this->assets->addCss("//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css", false);
    $this->assets->addCss("css/style.css", true);
    $this->assets->addCss("css/extra.css");
}
集合(Collections)

集合即是把一同类的资源放在一些,资源管理器隐含的创建了两个集合:css和js. 当然我们可以创建其它的集合以归类其它的资源, 这样我们可以很容易的 在视图里显示:

<?php

// HTML 头部的js资源
$headerCollection = $this->assets->collection("header");

$headerCollection->addJs("js/jquery.js");
$headerCollection->addJs("js/bootstrap.min.js");

// HTML尾部的js资源
$footerCollection = $this->assets->collection("footer");

$footerCollection->addJs("js/jquery.js");
$footerCollection->addJs("js/bootstrap.min.js");

然后在视图中如下使用:

<html>
    <head>
        <title>Some amazing website</title>

        <?php $this->assets->outputJs("header"); ?>
    </head>

    <body>
        <!-- ... -->

        <?php $this->assets->outputJs("footer"); ?>
    </body>
<html>

Volt语法:

<html>
    <head>
        <title>Some amazing website</title>

        {{ assets.outputCss("header") }}
    </head>

    <body>
        <!-- ... -->

        {{ assets.outputJs("footer") }}
    </body>
<html>
前缀(URL Prefixes)

集合可以添加前缀,这可以实现非常简单的更换服务器:

<?php

$footerCollection = $this->assets->collection("footer");

if ($config->environment === "development") {
    $footerCollection->setPrefix("/");
} else {
    $footerCollection->setPrefix("http:://cdn.example.com/");
}

$footerCollection->addJs("js/jquery.js");
$footerCollection->addJs("js/bootstrap.min.js");

我们也可以使用链式语法,如下:

<?php

$headerCollection = $assets
    ->collection("header")
    ->setPrefix("http://cdn.example.com/")
    ->setLocal(false)
    ->addJs("js/jquery.js")
    ->addJs("js/bootstrap.min.js");
压缩与过滤(Minification/Filtering)

Phalcon\Assets 提供了内置的js及css压缩工具。 开发者可以设定资源管理器以确定对哪些资源进行压缩哪些资源不进行压缩。除了上面这些之外, 我们还可以使用Douglas Crockford书写的Jsmin压缩工具,及Ryan Day提供的CSSMin来对js及css文件进行压缩. 下面的例子中展示了如何使用集合对资源文件进行压缩:

<?php

$manager

    // 这些javascript资源位于html文件的底部
    ->collection("jsFooter")

    // 最终输出名
    ->setTargetPath("final.js")

    // 使用此uri显示资源
    ->setTargetUri("production/final.js")

    // 添加远程资源但不压缩
    ->addJs("code.jquery.com/jquery-1.10.0.min.js", false, false)

    // 这些资源必须要压缩
    ->addJs("common-functions.js")
    ->addJs("page-functions.js")

    // 把这些资源放入一个文件内
    ->join(true)

    // 使用内置的JsMin过滤器
    ->addFilter(
        new Phalcon\Assets\Filters\Jsmin()
    )

    // 使用自定义过滤器
    ->addFilter(
        new MyApp\Assets\Filters\LicenseStamper()
    );

开始部分我们通过资源管理器取得了一个命名的集合,集合中可以包含JavaScript或CSS资源但不能同时包含两个。一些资源可能位于远程的服务器上, 这些资源我们可以通过http取得。为了提高性能建议把远程的资源取到本地来,以减少加载远程资源的开销。

如上示例,addJs() 方法用于将资源添加到集合中,第二个参数表示当前资源是否为外部资源,第三个参数表示当前资源是否需要进行压缩:

<?php

// 这些Javscript文件放在页面的底端
$jsFooterCollection = $manager->collection("jsFooter");

// 添加远程资源但不压缩
$jsFooterCollection->addJs("code.jquery.com/jquery-1.10.0.min.js", false, false);

// These are local resources that must be filtered
// 添加本地资源并压缩
$jsFooterCollection->addJs("common-functions.js");
$jsFooterCollection->addJs("page-functions.js");

过滤器被注册到集合内,我们可以注册多个过滤器,资源内容被过滤的顺序和过滤器注册的顺序是一样的。

<?php

// 使用内置的Jsmin过滤器
$jsFooterCollection->addFilter(
    new Phalcon\Assets\Filters\Jsmin()
);

// 使用自定义的过滤器
$jsFooterCollection->addFilter(
    new MyApp\Assets\Filters\LicenseStamper()
);

注意:不管是内置的还是自定义的过滤器对集合来说他们都是透明的。最后一步用来确定所有的资源文件写到同一个文件中还是分开保存。如果要让集合中所有的资源文件合成 一个文件只需要使用:code:`join()`函数.

如果资源被写入同一文件,则我们需要定义使用哪一个文件来保存要写入的资源数据,及使用一个ur来展示资源。这两个设置可以使用 setTargetPath()setTargetUri() 两个函数来配置:

<?php

$jsFooterCollection->join(true);

// 设置最终输出文件
$jsFooterCollection->setTargetPath("public/production/final.js");

// 使用此uri引用js
$jsFooterCollection->setTargetUri("production/final.js");
内置过滤器(Built-In Filters)

Phalcon内置了两个过滤器以分别实现对JavaScript及CSS的压缩,由于二者是使用c实现的故极大的减少了性能上的开销:

过滤器 说明
Phalcon\Assets\Filters\Jsmin 压缩JavaScript文件即去除掉JavaScript解释器/编译器忽略的一些字符
Phalcon\Assets\Filters\Cssmin 压缩CSS文件即去除掉浏览器在渲染CSS时不需要的一些字符
自定义过滤器(Custom Filters)

除了使用Phalcon内置的过滤器外,开发者还可以创建自己的过滤器。这样我们就可以使用 YUI, Sass, Closure, 等。

<?php

use Phalcon\Assets\FilterInterface;

/**
 * 使用YUI过滤CSS内容
 *
 * @param string $contents
 * @return string
 */
class CssYUICompressor implements FilterInterface
{
    protected $_options;

    /**
     * CssYUICompressor 构造函数
     *
     * @param array $options
     */
    public function __construct(array $options)
    {
        $this->_options = $options;
    }

    /**
     * 执行过滤
     *
     * @param string $contents
     *
     * @return string
     */
    public function filter($contents)
    {
        // 保存字符吕内容到临时文件中
        file_put_contents("temp/my-temp-1.css", $contents);

        system(
            $this->_options["java-bin"] .
            " -jar " .
            $this->_options["yui"] .
            " --type css " .
            "temp/my-temp-file-1.css " .
            $this->_options["extra-options"] .
            " -o temp/my-temp-file-2.css"
        );

        // 返回文件内容
        return file_get_contents("temp/my-temp-file-2.css");
    }
}

用法:

<?php

// 取CSS集合
$css = $this->assets->get("head");

// 添加/启用YUI压缩器
$css->addFilter(
    new CssYUICompressor(
        [
            "java-bin"      => "/usr/local/bin/java",
            "yui"           => "/some/path/yuicompressor-x.y.z.jar",
            "extra-options" => "--charset utf8",
        ]
    )
);

In a previous example, we used a custom filter called LicenseStamper:

<?php

use Phalcon\Assets\FilterInterface;

/**
 * Adds a license message to the top of the file
 *
 * @param string $contents
 *
 * @return string
 */
class LicenseStamper implements FilterInterface
{
    /**
     * Do the filtering
     *
     * @param string $contents
     * @return string
     */
    public function filter($contents)
    {
        $license = "/* (c) 2015 Your Name Here */";

        return $license . PHP_EOL . PHP_EOL . $contents;
    }
}
自定义输出(Custom Output)

outputJs()outputCss() 方法可以依据不同的资源类来创建需要的HTML代码。我们可以重写这个方法或是手动的输出这些资源方法如下:

<?php

use Phalcon\Tag;

$jsCollection = $this->assets->collection("js");

foreach ($jsCollection as $resource) {
    echo Tag::javascriptInclude(
        $resource->getPath()
    );
}

Volt 模版引擎(Volt: Template Engine)

Volt 是一个用C为PHP编写的超快的并且对设计师友好的模板语言。Volt 提供一组辅助工具有助于你以一种更简单的的方式编写视图(Views)。 同时,Volt与Phalcon的其他组件高度集成在一起,就像你在应用中单独使用Volt一样。

_images/volt.jpg

Volt is inspired by Jinja, originally created by Armin Ronacher. Therefore many developers will be in familiar territory using the same syntax they have been using with similar template engines. Volt’s syntax and features have been enhanced with more elements and of course with the performance that developers have been accustomed to while working with Phalcon.

简介(Introduction)

Volt 视图被编译成纯PHP代码,所以基本上他们节省手工编写PHP代码的工作:

{# 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 %}
启用 Volt(Activating Volt)

和其他模板引擎一样,你需要将Volt模板注册到视图组件中,并设置模板文件通用后缀名,或者直接使用标准的后缀名”.phtml”才能正常使用:

<?php

use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;

// Register Volt as a service
$di->set(
    "voltService",
    function ($view, $di) {
        $volt = new Volt($view, $di);

        $volt->setOptions(
            [
                "compiledPath"      => "../app/compiled-templates/",
                "compiledExtension" => ".compiled",
            ]
        );

        return $volt;
    }
);

// Register Volt as template engine
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../app/views/");

        $view->registerEngines(
            [
                ".volt" => "voltService",
            ]
        );

        return $view;
    }
);

使用标准的”.phtml” 后缀名:

<?php

$view->registerEngines(
    [
        ".phtml" => "voltService",
    ]
);

You don’t have to specify the Volt Service in the DI; you can also use the Volt engine with the default settings:

<?php

$view->registerEngines(
    [
        ".volt" => "Phalcon\\Mvc\\View\\Engine\\Volt",
    ]
);

If you do not want to reuse Volt as a service, you can pass an anonymous function to register the engine instead of a service name:

<?php

use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;

// Register Volt as template engine with an anonymous function
$di->set(
    "view",
    function () {
        $view = new \Phalcon\Mvc\View();

        $view->setViewsDir("../app/views/");

        $view->registerEngines(
            [
                ".volt" => function ($view, $di) {
                    $volt = new Volt($view, $di);

                    // Set some options here

                    return $volt;
                }
            ]
        );

        return $view;
    }
);

The following options are available in Volt:

Option Description Default
compiledPath A writable path where the compiled PHP templates will be placed ./
compiledExtension An additional extension appended to the compiled PHP file .php
compiledSeparator Volt replaces the directory separators / and \ by this separator in order to create a single file in the compiled directory %%
stat Whether Phalcon must check if exists differences between the template file and its compiled path true
compileAlways Tell Volt if the templates must be compiled in each request or only when they change false
prefix Allows to prepend a prefix to the templates in the compilation path null
autoescape Enables globally autoescape of HTML false

The compilation path is generated according to the above options, if the developer wants total freedom defining the compilation path, an anonymous function can be used to generate it, this function receives the relative path to the template in the views directory. The following examples show how to change the compilation path dynamically:

<?php

// Just append the .php extension to the template path
// leaving the compiled templates in the same directory
$volt->setOptions(
    [
        "compiledPath" => function ($templatePath) {
            return $templatePath . ".php";
        }
    ]
);

// Recursively create the same structure in another directory
$volt->setOptions(
    [
        "compiledPath" => function ($templatePath) {
            $dirName = dirname($templatePath);

            if (!is_dir("cache/" . $dirName)) {
                mkdir("cache/" . $dirName);
            }

            return "cache/" . $dirName . "/". $templatePath . ".php";
        }
    ]
);
基本用法(Basic Usage)

视图通常由Volt模板代码和HTML代码生成,甚至也含有PHP代码。Volt模板中有一些特殊分隔符的用法: {% ... %} 用于执行流程控制语句如if判断、for循环及赋值处理等等, {{ ... }} 用于在模板中输出表达式的执行结果。

下面例子介绍了一些基础用法:

{# app/views/posts/show.phtml #}
<!DOCTYPE html>
<html>
    <head>
        <title>{{ title }} - An example blog</title>
    </head>
    <body>

        {% if show_navigation %}
            <ul id="navigation">
                {% for item in menu %}
                    <li>
                        <a href="{{ item.href }}">
                            {{ item.caption }}
                        </a>
                    </li>
                {% endfor %}
            </ul>
        {% endif %}

        <h1>{{ post.title }}</h1>

        <div class="content">
            {{ post.content }}
        </div>

    </body>
</html>

使用 Phalcon\Mvc\View 实例可以从控制器中把变量传递给视图。 在下面的示例中,有四个变量传递给了视图: show_navigation, menu, title and post:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function showAction()
    {
        $post = Post::findFirst();
        $menu = Menu::findFirst();

        $this->view->show_navigation = true;
        $this->view->menu            = $menu;
        $this->view->title           = $post->title;
        $this->view->post            = $post;

        // Or...

        $this->view->setVar("show_navigation", true);
        $this->view->setVar("menu",            $menu);
        $this->view->setVar("title",           $post->title);
        $this->view->setVar("post",            $post);
    }
}
变量(Variables)

对象变量可能有一些属性值,可以使用 foo.bar 的方式来访问。如果传递的是一个数组变量,则必须使用 foo['bar'] 的方式来访问。

{{ post.title }} {# for $post->title #}
{{ post['title'] }} {# for $post['title'] #}
过滤器(Filters)

模板中的变量可以通过过滤器进行格式化。操作符 | 适用于对变量进行格式化:

{{ post.title|e }}
{{ post.content|striptags }}
{{ name|capitalize|trim }}

以下是Volt模板内置的过滤器列表:

Filter Description
e Applies Phalcon\Escaper->escapeHtml() to the value
escape Applies Phalcon\Escaper->escapeHtml() to the value
escape_css Applies Phalcon\Escaper->escapeCss() to the value
escape_js Applies Phalcon\Escaper->escapeJs() to the value
escape_attr Applies Phalcon\Escaper->escapeHtmlAttr() to the value
trim Applies the trim PHP function to the value. Removing extra spaces
left_trim Applies the ltrim PHP function to the value. Removing extra spaces
right_trim Applies the rtrim PHP function to the value. Removing extra spaces
striptags Applies the striptags PHP function to the value. Removing HTML tags
slashes Applies the slashes PHP function to the value. Escaping values
stripslashes Applies the stripslashes PHP function to the value. Removing escaped quotes
capitalize Capitalizes a string by applying the ucwords PHP function to the value
lower Change the case of a string to lowercase
upper Change the case of a string to uppercase
length Counts the string length or how many items are in an array or object
nl2br Changes newlines \n by line breaks (<br />). Uses the PHP function nl2br
sort Sorts an array using the PHP function asort
keys Returns the array keys using array_keys
join Joins the array parts using a separator join
format Formats a string using sprintf.
json_encode Converts a value into its JSON representation
json_decode Converts a value from its JSON representation to a PHP representation
abs Applies the abs PHP function to a value.
url_encode Applies the urlencode PHP function to the value
default Sets a default value in case that the evaluated expression is empty (is not set or evaluates to a falsy value)
convert_encoding Converts a string from one charset to another

Examples:

{# e or escape filter #}
{{ "<h1>Hello<h1>"|e }}
{{ "<h1>Hello<h1>"|escape }}

{# trim filter #}
{{ "   hello   "|trim }}

{# striptags filter #}
{{ "<h1>Hello<h1>"|striptags }}

{# slashes filter #}
{{ "'this is a string'"|slashes }}

{# stripslashes filter #}
{{ "\'this is a string\'"|stripslashes }}

{# capitalize filter #}
{{ "hello"|capitalize }}

{# lower filter #}
{{ "HELLO"|lower }}

{# upper filter #}
{{ "hello"|upper }}

{# length filter #}
{{ "robots"|length }}
{{ [1, 2, 3]|length }}

{# nl2br filter #}
{{ "some\ntext"|nl2br }}

{# sort filter #}
{% set sorted = [3, 1, 2]|sort %}

{# keys filter #}
{% set keys = ['first': 1, 'second': 2, 'third': 3]|keys %}

{# join filter #}
{% set joined = "a".."z"|join(",") %}

{# format filter #}
{{ "My real name is %s"|format(name) }}

{# json_encode filter #}
{% set encoded = robots|json_encode %}

{# json_decode filter #}
{% set decoded = '{"one":1,"two":2,"three":3}'|json_decode %}

{# url_encode filter #}
{{ post.permanent_link|url_encode }}

{# convert_encoding filter #}
{{ "désolé"|convert_encoding('utf8', 'latin1') }}
注释(Comments)

Comments may also be added to a template using the {# ... #} delimiters. All text inside them is just ignored in the final output:

{# note: this is a comment
    {% set price = 100; %}
#}
流程控制列表(List of Control Structures)

Volt provides a set of basic but powerful control structures for use in templates:

循环语句 For

Loop over each item in a sequence. The following example shows how to traverse a set of “robots” and print his/her name:

<h1>Robots</h1>
<ul>
    {% for robot in robots %}
        <li>
            {{ robot.name|e }}
        </li>
    {% endfor %}
</ul>

for-loops can also be nested:

<h1>Robots</h1>
{% for robot in robots %}
    {% for part in robot.parts %}
        Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
    {% endfor %}
{% endfor %}

You can get the element “keys” as in the PHP counterpart using the following syntax:

{% set numbers = ['one': 1, 'two': 2, 'three': 3] %}

{% for name, value in numbers %}
    Name: {{ name }} Value: {{ value }}
{% endfor %}

An “if” evaluation can be optionally set:

{% set numbers = ['one': 1, 'two': 2, 'three': 3] %}

{% for value in numbers if value < 2 %}
    Value: {{ value }}
{% endfor %}

{% for name, value in numbers if name !== 'two' %}
    Name: {{ name }} Value: {{ value }}
{% endfor %}

If an ‘else’ is defined inside the ‘for’, it will be executed if the expression in the iterator result in zero iterations:

<h1>Robots</h1>
{% for robot in robots %}
    Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
{% else %}
    There are no robots to show
{% endfor %}

Alternative syntax:

<h1>Robots</h1>
{% for robot in robots %}
    Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
{% elsefor %}
    There are no robots to show
{% endfor %}
循环控制(Loop Controls)

The ‘break’ and ‘continue’ statements can be used to exit from a loop or force an iteration in the current block:

{# skip the even robots #}
{% for index, robot in robots %}
    {% if index is even %}
        {% continue %}
    {% endif %}
    ...
{% endfor %}
{# exit the foreach on the first even robot #}
{% for index, robot in robots %}
    {% if index is even %}
        {% break %}
    {% endif %}
    ...
{% endfor %}
条件判断语句 If

As PHP, an “if” statement checks if an expression is evaluated as true or false:

<h1>Cyborg Robots</h1>
<ul>
    {% for robot in robots %}
        {% if robot.type === "cyborg" %}
            <li>{{ robot.name|e }}</li>
        {% endif %}
    {% endfor %}
</ul>

The else clause is also supported:

<h1>Robots</h1>
<ul>
    {% for robot in robots %}
        {% if robot.type === "cyborg" %}
            <li>{{ robot.name|e }}</li>
        {% else %}
            <li>{{ robot.name|e }} (not a cyborg)</li>
        {% endif %}
    {% endfor %}
</ul>

The ‘elseif’ control flow structure can be used together with if to emulate a ‘switch’ block:

{% if robot.type === "cyborg" %}
    Robot is a cyborg
{% elseif robot.type === "virtual" %}
    Robot is virtual
{% elseif robot.type === "mechanical" %}
    Robot is mechanical
{% endif %}
循环上下文(Loop Context)

A special variable is available inside ‘for’ loops providing you information about

Variable Description
loop.index The current iteration of the loop. (1 indexed)
loop.index0 The current iteration of the loop. (0 indexed)
loop.revindex The number of iterations from the end of the loop (1 indexed)
loop.revindex0 The number of iterations from the end of the loop (0 indexed)
loop.first True if in the first iteration.
loop.last True if in the last iteration.
loop.length The number of items to iterate
{% for robot in robots %}
    {% if loop.first %}
        <table>
            <tr>
                <th>#</th>
                <th>Id</th>
                <th>Name</th>
            </tr>
    {% endif %}
            <tr>
                <td>{{ loop.index }}</td>
                <td>{{ robot.id }}</td>
                <td>{{ robot.name }}</td>
            </tr>
    {% if loop.last %}
        </table>
    {% endif %}
{% endfor %}
赋值(Assignments)

Variables may be changed in a template using the instruction “set”:

{% set fruits = ['Apple', 'Banana', 'Orange'] %}

{% set name = robot.name %}

Multiple assignments are allowed in the same instruction:

{% set fruits = ['Apple', 'Banana', 'Orange'], name = robot.name, active = true %}

Additionally, you can use compound assignment operators:

{% set price += 100.00 %}

{% set age *= 5 %}

The following operators are available:

Operator Description
= Standard Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
表达式(Expressions)

Volt provides a basic set of expression support, including literals and common operators.

A expression can be evaluated and printed using the ‘{{‘ and ‘}}’ delimiters:

{{ (1 + 1) * 2 }}

If an expression needs to be evaluated without be printed the ‘do’ statement can be used:

{% do (1 + 1) * 2 %}
字面值(Literals)

The following literals are supported:

Filter Description
“this is a string” Text between double quotes or single quotes are handled as strings
100.25 Numbers with a decimal part are handled as doubles/floats
100 Numbers without a decimal part are handled as integers
false Constant “false” is the boolean false value
true Constant “true” is the boolean true value
null Constant “null” is the Null value
数组(Arrays)

Whether you’re using PHP 5.3 or >= 5.4 you can create arrays by enclosing a list of values in square brackets:

{# Simple array #}
{{ ['Apple', 'Banana', 'Orange'] }}

{# Other simple array #}
{{ ['Apple', 1, 2.5, false, null] }}

{# Multi-Dimensional array #}
{{ [[1, 2], [3, 4], [5, 6]] }}

{# Hash-style array #}
{{ ['first': 1, 'second': 4/2, 'third': '3'] }}

花括号也能用来定义数组或关联数组:

{% set myArray = {'Apple', 'Banana', 'Orange'} %}
{% set myHash  = {'first': 1, 'second': 4/2, 'third': '3'} %}
算术运算(Math)

你可以在模板里面使用下列操作符来进行算术运算:

Operator Description
+ Perform an adding operation. {{ 2 + 3 }} returns 5
- Perform a substraction operation {{ 2 - 3 }} returns -1
* Perform a multiplication operation {{ 2 * 3 }} returns 6
/ Perform a division operation {{ 10 / 2 }} returns 5
% Calculate the remainder of an integer division {{ 10 % 3 }} returns 1
比较运算(Comparisons)

The following comparison operators are available:

Operator Description
== Check whether both operands are equal
!= Check whether both operands aren’t equal
<> Check whether both operands aren’t equal
> Check whether left operand is greater than right operand
< Check whether left operand is less than right operand
<= Check whether left operand is less or equal than right operand
>= Check whether left operand is greater or equal than right operand
=== Check whether both operands are identical
!== Check whether both operands aren’t identical
逻辑运算(Logic)

Logic operators are useful in the “if” expression evaluation to combine multiple tests:

Operator Description
or Return true if the left or right operand is evaluated as true
and Return true if both left and right operands are evaluated as true
not Negates an expression
( expr ) Parenthesis groups expressions
其他操作(Other Operators)

Additional operators seen the following operators are available:

Operator Description
~ Concatenates both operands {{ "hello " ~ "world" }}
| Applies a filter in the right operand to the left {{ "hello"|uppercase }}
.. Creates a range {{ 'a'..'z' }} {{ 1..10 }}
is Same as == (equals), also performs tests
in To check if an expression is contained into other expressions if "a" in "abc"
is not Same as != (not equals)
'a' ? 'b' : 'c' Ternary operator. The same as the PHP ternary operator
++ Increments a value
-- Decrements a value

下面的示例显示了如何使用操作符:

{% set robots = ['Voltron', 'Astro Boy', 'Terminator', 'C3PO'] %}

{% for index in 0..robots|length %}
    {% if robots[index] is defined %}
        {{ "Name: " ~ robots[index] }}
    {% endif %}
{% endfor %}
测试运算(Tests)

Tests can be used to test if a variable has a valid expected value. The operator “is” is used to perform the tests:

{% set robots = ['1': 'Voltron', '2': 'Astro Boy', '3': 'Terminator', '4': 'C3PO'] %}

{% for position, name in robots %}
    {% if position is odd %}
        {{ name }}
    {% endif %}
{% endfor %}

The following built-in tests are available in Volt:

Test Description
defined Checks if a variable is defined (isset())
empty Checks if a variable is empty
even Checks if a numeric value is even
odd Checks if a numeric value is odd
numeric Checks if value is numeric
scalar Checks if value is scalar (not an array or object)
iterable Checks if a value is iterable. Can be traversed by a “for” statement
divisibleby Checks if a value is divisible by other value
sameas Checks if a value is identical to other value
type Checks if a value is of the specified type

More examples:

{% if robot is defined %}
    The robot variable is defined
{% endif %}

{% if robot is empty %}
    The robot is null or isn't defined
{% endif %}

{% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 3: 'Bender'] %}
    {% if key is even %}
        {{ name }}
    {% endif %}
{% endfor %}

{% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 3: 'Bender'] %}
    {% if key is odd %}
        {{ name }}
    {% endif %}
{% endfor %}

{% for key, name in [1: 'Voltron', 2: 'Astroy Boy', 'third': 'Bender'] %}
    {% if key is numeric %}
        {{ name }}
    {% endif %}
{% endfor %}

{% set robots = [1: 'Voltron', 2: 'Astroy Boy'] %}
{% if robots is iterable %}
    {% for robot in robots %}
        ...
    {% endfor %}
{% endif %}

{% set world = "hello" %}
{% if world is sameas("hello") %}
    {{ "it's hello" }}
{% endif %}

{% set external = false %}
{% if external is type('boolean') %}
    {{ "external is false or true" }}
{% endif %}
宏定义(Macros)

Macros can be used to reuse logic in a template, they act as PHP functions, can receive parameters and return values:

{# Macro "display a list of links to related topics" #}
{%- macro related_bar(related_links) %}
    <ul>
        {%- for link in related_links %}
            <li>
                <a href="{{ url(link.url) }}" title="{{ link.title|striptags }}">
                    {{ link.text }}
                </a>
            </li>
        {%- endfor %}
    </ul>
{%- endmacro %}

{# Print related links #}
{{ related_bar(links) }}

<div>This is the content</div>

{# Print related links again #}
{{ related_bar(links) }}

When calling macros, parameters can be passed by name:

{%- macro error_messages(message, field, type) %}
    <div>
        <span class="error-type">{{ type }}</span>
        <span class="error-field">{{ field }}</span>
        <span class="error-message">{{ message }}</span>
    </div>
{%- endmacro %}

{# Call the macro #}
{{ error_messages('type': 'Invalid', 'message': 'The name is invalid', 'field': 'name') }}

Macros can return values:

{%- macro my_input(name, class) %}
    {% return text_field(name, 'class': class) %}
{%- endmacro %}

{# Call the macro #}
{{ '<p>' ~ my_input('name', 'input-text') ~ '</p>' }}

And receive optional parameters:

{%- macro my_input(name, class="input-text") %}
    {% return text_field(name, 'class': class) %}
{%- endmacro %}

{# Call the macro #}
{{ '<p>' ~ my_input('name') ~ '</p>' }}
{{ '<p>' ~ my_input('name', 'input-text') ~ '</p>' }}
使用标签助手(Using Tag Helpers)

Volt is highly integrated with Phalcon\Tag, so it’s easy to use the helpers provided by that component in a Volt template:

{{ javascript_include("js/jquery.js") }}

{{ form('products/save', 'method': 'post') }}

    <label for="name">Name</label>
    {{ text_field("name", "size": 32) }}

    <label for="type">Type</label>
    {{ select("type", productTypes, 'using': ['id', 'name']) }}

    {{ submit_button('Send') }}

{{ end_form() }}

The following PHP is generated:

<?php echo Phalcon\Tag::javascriptInclude("js/jquery.js") ?>

<?php echo Phalcon\Tag::form(array('products/save', 'method' => 'post')); ?>

    <label for="name">Name</label>
    <?php echo Phalcon\Tag::textField(array('name', 'size' => 32)); ?>

    <label for="type">Type</label>
    <?php echo Phalcon\Tag::select(array('type', $productTypes, 'using' => array('id', 'name'))); ?>

    <?php echo Phalcon\Tag::submitButton('Send'); ?>

{{ end_form() }}

To call a Phalcon\Tag helper, you only need to call an uncamelized version of the method:

Method Volt function
Phalcon\Tag::linkTo link_to
Phalcon\Tag::textField text_field
Phalcon\Tag::passwordField password_field
Phalcon\Tag::hiddenField hidden_field
Phalcon\Tag::fileField file_field
Phalcon\Tag::checkField check_field
Phalcon\Tag::radioField radio_field
Phalcon\Tag::dateField date_field
Phalcon\Tag::emailField email_field
Phalcon\Tag::numericField numeric_field
Phalcon\Tag::submitButton submit_button
Phalcon\Tag::selectStatic select_static
Phalcon\Tag::select select
Phalcon\Tag::textArea text_area
Phalcon\Tag::form form
Phalcon\Tag::endForm end_form
Phalcon\Tag::getTitle get_title
Phalcon\Tag::stylesheetLink stylesheet_link
Phalcon\Tag::javascriptInclude javascript_include
Phalcon\Tag::image image
Phalcon\Tag::friendlyTitle friendly_title
函数(Functions)

The following built-in functions are available in Volt:

Name Description
content Includes the content produced in a previous rendering stage
get_content Same as content
partial Dynamically loads a partial view in the current template
super Render the contents of the parent block
time Calls the PHP function with the same name
date Calls the PHP function with the same name
dump Calls the PHP function var_dump()
version Returns the current version of the framework
constant Reads a PHP constant
url Generate a URL using the ‘url’ service
视图集成(View Integration)

Also, Volt is integrated with Phalcon\Mvc\View, you can play with the view hierarchy and include partials as well:

{{ content() }}

<!-- Simple include of a partial -->
<div id="footer">{{ partial("partials/footer") }}</div>

<!-- Passing extra variables -->
<div id="footer">{{ partial("partials/footer", ['links': links]) }}</div>

A partial is included in runtime, Volt also provides “include”, this compiles the content of a view and returns its contents as part of the view which was included:

{# Simple include of a partial #}
<div id="footer">
    {% include "partials/footer" %}
</div>

{# Passing extra variables #}
<div id="footer">
    {% include "partials/footer" with ['links': links] %}
</div>
包含(Include)

‘include’ has a special behavior that will help us improve performance a bit when using Volt, if you specify the extension when including the file and it exists when the template is compiled, Volt can inline the contents of the template in the parent template where it’s included. Templates aren’t inlined if the ‘include’ have variables passed with ‘with’:

{# The contents of 'partials/footer.volt' is compiled and inlined #}
<div id="footer">
    {% include "partials/footer.volt" %}
</div>
Partial vs Include

Keep the following points in mind when choosing to use the “partial” function or “include”:

  • ‘Partial’ 既可以引入Volt模板,也可以引入其他模板引擎的模板
  • ‘Partial’ 在引入模板的时候,可以传递表达式(如变量)
  • ‘Partial’ 更适合引入经常有变动的模板
  • ‘Include’ 是引入编译后的模板内容,以提升性能
  • ‘Include’ 只能引入Volt模板
  • ‘Include’ 在编译时须引入现有的模板
模版的继承(Template Inheritance)

你可以创建基础模板,供其他模板继承,达到代码复用的目的。在基础模板中使用 block 定义代码块,则子模板可以实现重写功能。 我们假设有一个这样的基础模板:

{# templates/base.volt #}
<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
        {% endblock %}

        <title>{% block title %}{% endblock %} - My Webpage</title>
    </head>

    <body>
        <div id="content">{% block content %}{% endblock %}</div>

        <div id="footer">
            {% block footer %}&copy; Copyright 2015, All rights reserved.{% endblock %}
        </div>
    </body>
</html>

其他的模板继承了基础模板后,会重写基础模板中的 block 代码块:

{% extends "templates/base.volt" %}

{% block title %}Index{% endblock %}

{% block head %}<style type="text/css">.important { color: #336699; }</style>{% endblock %}

{% block content %}
    <h1>Index</h1>
    <p class="important">Welcome on my awesome homepage.</p>
{% endblock %}

在子模板中并不需要全部重写基础模板中的 block 块,按需要重写部分即可。最终输出如下示例:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">.important { color: #336699; }</style>

        <title>Index - My Webpage</title>
    </head>

    <body>
        <div id="content">
            <h1>Index</h1>
            <p class="important">Welcome on my awesome homepage.</p>
        </div>

        <div id="footer">
            &copy; Copyright 2015, All rights reserved.
        </div>
    </body>
</html>
多重继承(Multiple Inheritance)

子模板也可以被其他模板继承,下面的示例演示了模板的多重继承:

{# main.volt #}
<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
    </head>

    <body>
        {% block content %}{% endblock %}
    </body>
</html>

“layout.volt” 继承 “main.volt”

{# layout.volt #}
{% extends "main.volt" %}

{% block content %}

    <h1>Table of contents</h1>

{% endblock %}

“index.volt” 又继承了 “layout.volt”:

{# index.volt #}
{% extends "layout.volt" %}

{% block content %}

    {{ super() }}

    <ul>
        <li>Some option</li>
        <li>Some other option</li>
    </ul>

{% endblock %}

渲染 “index.volt” 后输出:

<!DOCTYPE html>
<html>
    <head>
        <title>Title</title>
    </head>

    <body>

        <h1>Table of contents</h1>

        <ul>
            <li>Some option</li>
            <li>Some other option</li>
        </ul>

    </body>
</html>

注意示例中调用的 super() 方法,此方法用于获取父模板中渲染的内容。

As partials, the path set to “extends” is a relative path under the current views directory (i.e. app/views/).

通常情况下,出于性能方面的考虑,Volt模板引擎在重新编译模板时只会检查子模板中的内容变更。 所以建议设置Volt模板引擎的选项参数 'compileAlways' => true。这样模板会实时编译,并检查父模板中的内容变更。
自动编码模式(Autoescape mode)

You can enable auto-escaping of all variables printed in a block using the autoescape mode:

Manually escaped: {{ robot.name|e }}

{% autoescape true %}
    Autoescaped: {{ robot.name }}
    {% autoescape false %}
        No Autoescaped: {{ robot.name }}
    {% endautoescape %}
{% endautoescape %}
扩展 Volt(Extending Volt)

Unlike other template engines, Volt itself is not required to run the compiled templates. Once the templates are compiled there is no dependence on Volt. With performance independence in mind, Volt only acts as a compiler for PHP templates.

The Volt compiler allow you to extend it adding more functions, tests or filters to the existing ones.

函数(Functions)

Functions act as normal PHP functions, a valid string name is required as function name. Functions can be added using two strategies, returning a simple string or using an anonymous function. Always is required that the chosen strategy returns a valid PHP string expression:

<?php

use Phalcon\Mvc\View\Engine\Volt;

$volt = new Volt($view, $di);

$compiler = $volt->getCompiler();

// This binds the function name 'shuffle' in Volt to the PHP function 'str_shuffle'
$compiler->addFunction("shuffle", "str_shuffle");

Register the function with an anonymous function. This case we use $resolvedArgs to pass the arguments exactly as were passed in the arguments:

<?php

$compiler->addFunction(
    "widget",
    function ($resolvedArgs, $exprArgs) {
        return "MyLibrary\\Widgets::get(" . $resolvedArgs . ")";
    }
);

Treat the arguments independently and unresolved:

<?php

$compiler->addFunction(
    "repeat",
    function ($resolvedArgs, $exprArgs) use ($compiler) {
        // Resolve the first argument
        $firstArgument = $compiler->expression($exprArgs[0]['expr']);

        // Checks if the second argument was passed
        if (isset($exprArgs[1])) {
            $secondArgument = $compiler->expression($exprArgs[1]['expr']);
        } else {
            // Use '10' as default
            $secondArgument = '10';
        }

        return "str_repeat(" . $firstArgument . ", " . $secondArgument . ")";
    }
);

Generate the code based on some function availability:

<?php

$compiler->addFunction(
    "contains_text",
    function ($resolvedArgs, $exprArgs) {
        if (function_exists("mb_stripos")) {
            return "mb_stripos(" . $resolvedArgs . ")";
        } else {
            return "stripos(" . $resolvedArgs . ")";
        }
    }
);

Built-in functions can be overridden adding a function with its name:

<?php

// Replace built-in function dump
$compiler->addFunction("dump", "print_r");
过滤器(Filters)

A filter has the following form in a template: leftExpr|name(optional-args). Adding new filters is similar as seen with the functions:

<?php

// This creates a filter 'hash' that uses the PHP function 'md5'
$compiler->addFilter("hash", "md5");
<?php

$compiler->addFilter(
    "int",
    function ($resolvedArgs, $exprArgs) {
        return "intval(" . $resolvedArgs . ")";
    }
);

Built-in filters can be overridden adding a function with its name:

<?php

// Replace built-in filter 'capitalize'
$compiler->addFilter("capitalize", "lcfirst");
扩展(Extensions)

With extensions the developer has more flexibility to extend the template engine, and override the compilation of a specific instruction, change the behavior of an expression or operator, add functions/filters, and more.

An extension is a class that implements the events triggered by Volt as a method of itself.

For example, the class below allows to use any PHP function in Volt:

<?php

class PhpFunctionExtension
{
    /**
     * This method is called on any attempt to compile a function call
     */
    public function compileFunction($name, $arguments)
    {
        if (function_exists($name)) {
            return $name . "(". $arguments . ")";
        }
    }
}

The above class implements the method ‘compileFunction’ which is invoked before any attempt to compile a function call in any template. The purpose of the extension is to verify if a function to be compiled is a PHP function allowing to call it from the template. Events in extensions must return valid PHP code, this will be used as result of the compilation instead of the one generated by Volt. If an event doesn’t return an string the compilation is done using the default behavior provided by the engine.

The following compilation events are available to be implemented in extensions:

Event/Method Description
compileFunction Triggered before trying to compile any function call in a template
compileFilter Triggered before trying to compile any filter call in a template
resolveExpression Triggered before trying to compile any expression. This allows the developer to override operators
compileStatement Triggered before trying to compile any expression. This allows the developer to override any statement

Volt extensions must be in registered in the compiler making them available in compile time:

<?php

// Register the extension in the compiler
$compiler->addExtension(
    new PhpFunctionExtension()
);
缓存视图片段(Caching view fragments)

With Volt it’s easy cache view fragments. This caching improves performance preventing that the contents of a block from being executed by PHP each time the view is displayed:

{% cache "sidebar" %}
    <!-- generate this content is slow so we are going to cache it -->
{% endcache %}

Setting a specific number of seconds:

{# cache the sidebar by 1 hour #}
{% cache "sidebar" 3600 %}
    <!-- generate this content is slow so we are going to cache it -->
{% endcache %}

Any valid expression can be used as cache key:

{% cache ("article-" ~ post.id) 3600 %}

    <h1>{{ post.title }}</h1>

    <p>{{ post.content }}</p>

{% endcache %}

The caching is done by the Phalcon\Cache component via the view component. Learn more about how this integration works in the section “Caching View Fragments”.

注入服务到模版(Inject Services into a Template)

If a service container (DI) is available for Volt, you can use the services by only accessing the name of the service in the template:

{# Inject the 'flash' service #}
<div id="messages">{{ flash.output() }}</div>

{# Inject the 'security' service #}
<input type="hidden" name="token" value="{{ security.getToken() }}">
独立的组件(Stand-alone component)

Using Volt in a stand-alone mode can be demonstrated below:

<?php

use Phalcon\Mvc\View\Engine\Volt\Compiler as VoltCompiler;

// Create a compiler
$compiler = new VoltCompiler();

// Optionally add some options
$compiler->setOptions(
    [
        // ...
    ]
);

// Compile a template string returning PHP code
echo $compiler->compileString(
    "{{ 'hello' }}"
);

// Compile a template in a file specifying the destination file
$compiler->compileFile(
    "layouts/main.volt",
    "cache/layouts/main.volt.php"
);

// Compile a template in a file based on the options passed to the compiler
$compiler->compile(
    "layouts/main.volt"
);

// Require the compiled templated (optional)
require $compiler->getCompiledTemplatePath();
外部资源(External Resources)

MVC 应用(MVC Applications)

在Phalcon,策划MVC操作背后的全部困难工作通常都可以 通过 Phalcon\Mvc\Application 做到。这个组件封装了全部后端所需要的复杂 操作,实例化每一个需要用到的组件并与项目整合在一起,从而使得MVC模式可以如期地运行。

单模块或多模块应用(Single or Multi Module Applications)

通过这个组件,你可以运行各式各样的MVC结构:

单模块(Single Module)

单一的MVC应用仅仅包含了一个模块。可以使用命名空间,但不是必需的。 这样类型的应用可能会有以下文件目录结构:

single/
    app/
        controllers/
        models/
        views/
    public/
        css/
        img/
        js/

如果未使用命名空间,以下的启动文件可用于编排MVC工作流:

<?php

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;

$loader = new Loader();

$loader->registerDirs(
    [
        "../apps/controllers/",
        "../apps/models/",
    ]
);

$loader->register();

$di = new FactoryDefault();

// 注册视图组件
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../apps/views/");

        return $view;
    }
);

$application = new Application($di);

try {
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo $e->getMessage();
}

如果使用了命名空间,则可以使用以下启动文件(译者注:主要区别在于使用$loader的方式):

<?php

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;

$loader = new Loader();

// 根据命名空间前缀加载
$loader->registerNamespaces(
    [
        "Single\\Controllers" => "../apps/controllers/",
        "Single\\Models"      => "../apps/models/",
    ]
);

$loader->register();

$di = new FactoryDefault();

// 注册调度器,并设置控制器的默认命名空间
$di->set(
    "dispatcher",
    function () {
        $dispatcher = new Dispatcher();

        $dispatcher->setDefaultNamespace("Single\\Controllers");

        return $dispatcher;
    }
);

// 注册视图组件
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../apps/views/");

        return $view;
    }
);

$application = new Application($di);

try {
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo $e->getMessage();
}
多模块(Multi Module)

多模块的应用使用了相同的文档根目录但拥有多个模块。在这种情况下,可以使用以下的文件目录结构:

multiple/
  apps/
    frontend/
       controllers/
       models/
       views/
       Module.php
    backend/
       controllers/
       models/
       views/
       Module.php
  public/
    css/
    img/
    js/

在apps/下的每一个目录都有自己的MVC结构。Module.php文件代表了各个模块不同的配置,如自动加载器和自定义服务:

<?php

namespace Multiple\Backend;

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;

class Module implements ModuleDefinitionInterface
{
    /**
     * 注册自定义加载器
     */
    public function registerAutoloaders(DiInterface $di = null)
    {
        $loader = new Loader();

        $loader->registerNamespaces(
            [
                "Multiple\\Backend\\Controllers" => "../apps/backend/controllers/",
                "Multiple\\Backend\\Models"      => "../apps/backend/models/",
            ]
        );

        $loader->register();
    }

    /**
     * 注册自定义服务
     */
    public function registerServices(DiInterface $di)
    {
        // Registering a dispatcher
        $di->set(
            "dispatcher",
            function () {
                $dispatcher = new Dispatcher();

                $dispatcher->setDefaultNamespace("Multiple\\Backend\\Controllers");

                return $dispatcher;
            }
        );

        // Registering the view component
        $di->set(
            "view",
            function () {
                $view = new View();

                $view->setViewsDir("../apps/backend/views/");

                return $view;
            }
        );
    }
}

还需要一个指定的启动文件来加载多模块的MVC架构:

<?php

use Phalcon\Mvc\Router;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;

$di = new FactoryDefault();

// 自定义路由
// More information how to set the router up https://docs.phalconphp.com/zh/latest/reference/routing.html
$di->set(
    "router",
    function () {
        $router = new Router();

        $router->setDefaultModule("frontend");

        $router->add(
            "/login",
            [
                "module"     => "backend",
                "controller" => "login",
                "action"     => "index",
            ]
        );

        $router->add(
            "/admin/products/:action",
            [
                "module"     => "backend",
                "controller" => "products",
                "action"     => 1,
            ]
        );

        $router->add(
            "/products/:action",
            [
                "controller" => "products",
                "action"     => 1,
            ]
        );

        return $router;
    }
);

// 创建应用
$application = new Application($di);

// 注册模块
$application->registerModules(
    [
        "frontend" => [
            "className" => "Multiple\\Frontend\\Module",
            "path"      => "../apps/frontend/Module.php",
        ],
        "backend"  => [
            "className" => "Multiple\\Backend\\Module",
            "path"      => "../apps/backend/Module.php",
        ]
    ]
);

    // 处理请求
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo $e->getMessage();
}

如果你想在启动文件保持模块的配置,你可以使用匿名函数来注册对应的模块:

<?php

use Phalcon\Mvc\View;

// 创建视图组件
$view = new View();

// 设置视图组件相关选项
// ...

// Register the installed modules
$application->registerModules(
    [
        "frontend" => function ($di) use ($view) {
            $di->setShared(
                "view",
                function () use ($view) {
                    $view->setViewsDir("../apps/frontend/views/");

                    return $view;
                }
            );
        },
        "backend" => function ($di) use ($view) {
            $di->setShared(
                "view",
                function () use ($view) {
                    $view->setViewsDir("../apps/backend/views/");

                    return $view;
                }
            );
        }
    ]
);

Phalcon\Mvc\Application 有多个模块注册时,通常 每个都是需要的,以便每一个被匹配到的路由都能返回一个有效的模块。每个已经注册的模块都有一个相关的类来提供建立和启动自身的函数。 而每个模块定义的类都必须实现registerAutoloaders()和registerServices()这两个方法,这两个函数会在模块即被执行时被 Phalcon\Mvc\Application 调用。

应用事件(Application Events)

Phalcon\Mvc\Application 可以把事件发送到 EventsManager (如果它激活的话)。 事件将被当作”application”类型被消费掉。目前已支持的事件如下:

事件名称 消费于
boot 当应用处理它首个请求时被执行
beforeStartModule 在初始化模块之前,仅当模块被注册时
afterStartModule 在初始化模块之后,仅当模块被注册时
beforeHandleRequest 在执行分发环前
afterHandleRequest 在执行分发环后

以下示例演示了如何将侦听器绑定到组件:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$eventsManager = new EventsManager();

$application->setEventsManager($eventsManager);

$eventsManager->attach(
    "application",
    function (Event $event, $application) {
        // ...
    }
);
外部资源(External Resources)

路由(Routing)

The router component allows you to define 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.

路由器组件用来定义处理接收到的请求的路由,指向相应的控制器或者处理程序。路由器只是简单解析一个URI获取这些信息。 路由器有两种模式:MVC模式以及匹配模式。第一种模式主要适合MVC应用。

定义路由(Defining Routes)

Phalcon\Mvc\Router 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:

Phalcon\Mvc\Router 提供高级路由支持。在MVC模式下,你可以定义路由并映射向需要的控制器/动作。 一个路由定义方法如下所示:

<?php

use Phalcon\Mvc\Router;

// Create the router
$router = new Router();

// Define a route
$router->add(
    "/admin/users/my-profile",
    [
        "controller" => "users",
        "action"     => "profile",
    ]
);

// Another route
$router->add(
    "/admin/users/change-password",
    [
        "controller" => "users",
        "action"     => "changePassword",
    ]
);

$router->handle();

add() 方法接受一个匹配模式作为第一个参数,一组可选的路径作为第二个参数。如上,如果URI就是/admin/users/my-profile的话, 那么 “users” 控制的 “profile” 方法将被调用。当然路由器并不马上就调用这个方法,它只是收集这些信息并且通知相应的组件( 比如 Phalcon\Mvc\Dispatcher )应该调用这个控制器的这个动作。

一个应用程序可以由很多路径,一个一个定义是一个非常笨重的工作。这种情况下我们可以创建一个更加灵活的路由:

<?php

use Phalcon\Mvc\Router;

// Create the router
$router = new Router();

// Define a route
$router->add(
    "/admin/:controller/a/:action/:params",
    [
        "controller" => 1,
        "action"     => 2,
        "params"     => 3,
    ]
);

在上面的例子中我们通过使用通配符定义了一个可以匹配多个URI的路由,比如,访问这个URL(/admin/users/a/delete/dave/301),那么:

Controller users
Action delete
Parameter dave
Parameter 301

The add() method receives a pattern that can optionally have predefined placeholders and regular expression modifiers. All the routing patterns must start with a forward slash character (/). The regular expression syntax used is the same as the PCRE regular expressions. Note that, it is not necessary to add regular expression delimiters. All route patterns are case-insensitive.

The second parameter defines how the matched parts should bind to the controller/action/parameters. Matching parts are placeholders or subpatterns delimited by parentheses (round brackets). In the example given above, the first subpattern matched (:controller) is the controller part of the route, the second the action and so on.

These placeholders help writing regular expressions that are more readable for developers and easier to understand. The following placeholders are supported:

Placeholder Regular Expression Usage
/:module /([a-zA-Z0-9\_\-]+) Matches a valid module name with alpha-numeric characters only
/:controller /([a-zA-Z0-9\_\-]+) Matches a valid controller name with alpha-numeric characters only
/:action /([a-zA-Z0-9\_]+) Matches a valid action name with alpha-numeric characters only
/:params (/.*)* Matches a list of optional words separated by slashes. Only use this placeholder at the end of a route
/:namespace /([a-zA-Z0-9\_\-]+) Matches a single level namespace name
/:int /([0-9]+) Matches an integer parameter

Controller names are camelized, this means that characters (-) and (_) are removed and the next character is uppercased. For instance, some_controller is converted to SomeController.

Since you can add many routes as you need using the add() method, the order in which routes are added indicate their relevance, latest routes added have more relevance than first added. Internally, all defined routes are traversed in reverse order until Phalcon\Mvc\Router finds the one that matches the given URI and processes it, while ignoring the rest.

参数名称(Parameters with Names)

下面的例子演示了如何定义路由参数:

<?php

$router->add(
    "/news/([0-9]{4})/([0-9]{2})/([0-9]{2})/:params",
    [
        "controller" => "posts",
        "action"     => "show",
        "year"       => 1, // ([0-9]{4})
        "month"      => 2, // ([0-9]{2})
        "day"        => 3, // ([0-9]{2})
        "params"     => 4, // :params
    ]
);

在上述示例中,路由规则里并没有定义 “controller” 或者 “action” 部分。它们已经被路由替换为(“posts” and “show”)。 用户不会知道请求当中实际分发到的是哪个控制器。在控制器内部,可以通过如下方式来接收参数:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction()
    {
        // Get "year" parameter
        $year = $this->dispatcher->getParam("year");

        // Get "month" parameter
        $month = $this->dispatcher->getParam("month");

        // Get "day" parameter
        $day = $this->dispatcher->getParam("day");

        // ...
    }
}

Note that the values of the parameters are obtained from the dispatcher. This happens because it is the component that finally interacts with the drivers of your application. Moreover, there is also another way to create named parameters as part of the pattern:

<?php

$router->add(
    "/documentation/{chapter}/{name}.{type:[a-z]+}",
    [
        "controller" => "documentation",
        "action"     => "show",
    ]
);

You can access their values in the same way as before:

<?php

use Phalcon\Mvc\Controller;

class DocumentationController extends Controller
{
    public function showAction()
    {
        // Get "name" parameter
        $name = $this->dispatcher->getParam("name");

        // Get "type" parameter
        $type = $this->dispatcher->getParam("type");

        // ...
    }
}
短语法(Short Syntax)

If you don’t like using an array to define the route paths, an alternative syntax is also available. The following examples produce the same result:

<?php

// Short form
$router->add(
    "/posts/{year:[0-9]+}/{title:[a-z\-]+}",
    "Posts::show"
);

// Array form
$router->add(
    "/posts/([0-9]+)/([a-z\-]+)",
    [
       "controller" => "posts",
       "action"     => "show",
       "year"       => 1,
       "title"      => 2,
    ]
);
混合使用数组和短语法(Mixing Array and Short Syntax)

Array and short syntax can be mixed to define a route, in this case note that named parameters automatically are added to the route paths according to the position on which they were defined:

<?php

// First position must be skipped because it is used for
// the named parameter 'country'
$router->add(
    "/news/{country:[a-z]{2}}/([a-z+])/([a-z\-+])",
    [
        "section" => 2, // Positions start with 2
        "article" => 3,
    ]
);
路由到模块(Routing to Modules)

你可以在路由规则中包含模块。这种用法特别适合于多模块的应用程序。It’s possible define a default route that includes a module wildcard:

<?php

use Phalcon\Mvc\Router;

$router = new Router(false);

$router->add(
    "/:module/:controller/:action/:params",
    [
        "module"     => 1,
        "controller" => 2,
        "action"     => 3,
        "params"     => 4,
    ]
);

在上述示例中,URL中必须总是含有模块名才能进行路由解析。比如URL: /admin/users/edit/sonny, 将会被路由解析为:

Module admin
Controller users
Action edit
Parameter sonny

你也可以将特定的路由规则绑定到特定的模块:

<?php

$router->add(
    "/login",
    [
        "module"     => "backend",
        "controller" => "login",
        "action"     => "index",
    ]
);

$router->add(
    "/products/:action",
    [
        "module"     => "frontend",
        "controller" => "products",
        "action"     => 1,
    ]
);

Or bind them to specific namespaces:

<?php

$router->add(
    "/:namespace/login",
    [
        "namespace"  => 1,
        "controller" => "login",
        "action"     => "index",
    ]
);

Namespaces/class names must be passed separated:

<?php

$router->add(
    "/login",
    [
        "namespace"  => "Backend\\Controllers",
        "controller" => "login",
        "action"     => "index",
    ]
);
限制 HTTP 请求传入方式(HTTP Method Restrictions)

当使用 add() 方法来添加路由规则时, 这条路由规则可以支持HTTP协议的任何数据传输方法。 有时我们需要限制路由规则只能匹配HTTP协议的某个方法,这在创建 RESTful 风格的应用程序时特别有用:

<?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",
    "Products::update"
)->via(
    [
        "POST",
        "PUT",
    ]
);
使用转换(Using conversors)

Conversors allow you to freely transform the route’s parameters before passing them to the dispatcher. The following examples show how to use them:

<?php

// The action name allows dashes, an action can be: /products/new-ipod-nano-4-generation
$route = $router->add(
    "/products/{slug:[a-z\-]+}",
    [
        "controller" => "products",
        "action"     => "show",
    ]
);

$route->convert(
    "slug",
    function ($slug) {
        // Transform the slug removing the dashes
        return str_replace("-", "", $slug);
    }
);

Another use case for conversors is binding a model into a route. This allows the model to be passed into the defined action directly:

<?php

// This example works off the assumption that the ID is being used as parameter in the url: /products/4
$route = $router->add(
    "/products/{id}",
    [
        "controller" => "products",
        "action"     => "show",
    ]
);

$route->convert(
    "id",
    function ($id) {
        // Fetch the model
        return Product::findFirstById($id);
    }
);
路由分组(Groups of Routes)

If a set of routes have common paths they can be grouped to easily maintain them:

<?php

use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;

$router = new Router();

// Create a group with a common module and controller
$blog = new RouterGroup(
    [
        "module"     => "blog",
        "controller" => "index",
    ]
);

// All the routes start with /blog
$blog->setPrefix("/blog");

// Add a route to the group
$blog->add(
    "/save",
    [
        "action" => "save",
    ]
);

// Add another route to the group
$blog->add(
    "/edit/{id}",
    [
        "action" => "edit",
    ]
);

// This route maps to a controller different than the default
$blog->add(
    "/blog",
    [
        "controller" => "blog",
        "action"     => "index",
    ]
);

// Add the group to the router
$router->mount($blog);

You can move groups of routes to separate files in order to improve the organization and code reusing in the application:

<?php

use Phalcon\Mvc\Router\Group as RouterGroup;

class BlogRoutes extends RouterGroup
{
    public function initialize()
    {
        // Default paths
        $this->setPaths(
            [
                "module"    => "blog",
                "namespace" => "Blog\\Controllers",
            ]
        );

        // All the routes start with /blog
        $this->setPrefix("/blog");

        // Add a route to the group
        $this->add(
            "/save",
            [
                "action" => "save",
            ]
        );

        // Add another route to the group
        $this->add(
            "/edit/{id}",
            [
                "action" => "edit",
            ]
        );

        // This route maps to a controller different than the default
        $this->add(
            "/blog",
            [
                "controller" => "blog",
                "action"     => "index",
            ]
        );
    }
}

Then mount the group in the router:

<?php

// Add the group to the router
$router->mount(
    new BlogRoutes()
);
匹配路由(Matching Routes)

A valid URI must be passed to the Router so that it can process it and find a matching route. By default, the routing URI is taken from the $_GET["_url"] variable that is created by the rewrite engine module. A couple of rewrite rules that work very well with Phalcon are:

RewriteEngine On
RewriteCond   %{REQUEST_FILENAME} !-d
RewriteCond   %{REQUEST_FILENAME} !-f
RewriteRule   ^((?s).*)$ index.php?_url=/$1 [QSA,L]

In this configuration, any requests to files or folders that don’t exist will be sent to index.php.

The following example shows how to use this component in stand-alone mode:

<?php

use Phalcon\Mvc\Router;

// Creating a router
$router = new Router();

// Define routes here if any
// ...

// Taking URI from $_GET["_url"]
$router->handle();

// Or Setting the URI value directly
$router->handle("/employees/edit/17");

// Getting the processed controller
echo $router->getControllerName();

// Getting the processed action
echo $router->getActionName();

// Get the matched route
$route = $router->getMatchedRoute();
路由命名(Naming Routes)

Each route that is added to the router is stored internally as a Phalcon\Mvc\Router\Route object. That class encapsulates all the details of each route. For instance, we can give a name to a path to identify it uniquely in our application. This is especially useful if you want to create URLs from it.

<?php

$route = $router->add(
    "/posts/{year}/{title}",
    "Posts::show"
);

$route->setName("show-posts");

Then, using for example the component Phalcon\Mvc\Url we can build routes from its name:

<?php

// Returns /posts/2012/phalcon-1-0-released
echo $url->get(
    [
        "for"   => "show-posts",
        "year"  => "2012",
        "title" => "phalcon-1-0-released",
    ]
);
范例(Usage Examples)

The following are examples of custom routes:

<?php

// Matches "/system/admin/a/edit/7001"
$router->add(
    "/system/:controller/a/:action/:params",
    [
        "controller" => 1,
        "action"     => 2,
        "params"     => 3,
    ]
);

// Matches "/es/news"
$router->add(
    "/([a-z]{2})/:controller",
    [
        "controller" => 2,
        "action"     => "index",
        "language"   => 1,
    ]
);

// Matches "/es/news"
$router->add(
    "/{language:[a-z]{2}}/:controller",
    [
        "controller" => 2,
        "action"     => "index",
    ]
);

// Matches "/admin/posts/edit/100"
$router->add(
    "/admin/:controller/:action/:int",
    [
        "controller" => 1,
        "action"     => 2,
        "id"         => 3,
    ]
);

// Matches "/posts/2015/02/some-cool-content"
$router->add(
    "/posts/([0-9]{4})/([0-9]{2})/([a-z\-]+)",
    [
        "controller" => "posts",
        "action"     => "show",
        "year"       => 1,
        "month"      => 2,
        "title"      => 4,
    ]
);

// Matches "/manual/en/translate.adapter.html"
$router->add(
    "/manual/([a-z]{2})/([a-z\.]+)\.html",
    [
        "controller" => "manual",
        "action"     => "show",
        "language"   => 1,
        "file"       => 2,
    ]
);

// Matches /feed/fr/le-robots-hot-news.atom
$router->add(
    "/feed/{lang:[a-z]+}/{blog:[a-z\-]+}\.{type:[a-z\-]+}",
    "Feed::get"
);

// Matches /api/v1/users/peter.json
$router->add(
    "/api/(v1|v2)/{method:[a-z]+}/{param:[a-z]+}\.(json|xml)",
    [
        "controller" => "api",
        "version"    => 1,
        "format"     => 4,
    ]
);
Beware of characters allowed in regular expression for controllers and namespaces. As these become class names and in turn they’re passed through the file system could be used by attackers to read unauthorized files. A safe regular expression is: /([a-zA-Z0-9\_\-]+)
默认行为(Default Behavior)

Phalcon\Mvc\Router has a default behavior that provides a very simple routing that always expects a URI that matches the following pattern: /:controller/:action/:params

For example, for a URL like this http://phalconphp.com/documentation/show/about.html, this router will translate it as follows:

Controller documentation
Action show
Parameter about.html

If you don’t want the router to have this behavior, you must create the router passing false as the first parameter:

<?php

use Phalcon\Mvc\Router;

// Create the router without default routes
$router = new Router(false);
设置默认路由(Setting the default route)

When your application is accessed without any route, the ‘/’ route is used to determine what paths must be used to show the initial page in your website/application:

<?php

$router->add(
    "/",
    [
        "controller" => "index",
        "action"     => "index",
    ]
);
没有找到路径(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(
    [
        "controller" => "index",
        "action"     => "route404",
    ]
);

This is typically for an Error 404 page.

设置默认路径(Setting default paths)

It’s possible to define default values for the module, controller or action. When a route is missing any of those paths they can be automatically filled by the router:

可以为通用路径中的 module, controller, action 定义默认值。当一个路由缺少其中任何一项时,路由器可以自动用默认值填充:

<?php

// Setting a specific default
$router->setDefaultModule("backend");
$router->setDefaultNamespace("Backend\\Controllers");
$router->setDefaultController("index");
$router->setDefaultAction("index");

// Using an array
$router->setDefaults(
    [
        "controller" => "index",
        "action"     => "index",
    ]
);
处理结尾额外的斜杆(Dealing with extra/trailing slashes)

Sometimes a route could be accessed with extra/trailing slashes. Those extra slashes would lead to produce a not-found status in the dispatcher. You can set up the router to automatically remove the slashes from the end of handled route:

<?php

use Phalcon\Mvc\Router;

$router = new Router();

// Remove trailing slashes automatically
$router->removeExtraSlashes(true);

Or, you can modify specific routes to optionally accept trailing slashes:

<?php

// The [/]{0,1} allows this route to have optionally have a trailing slash
$router->add(
    "/{language:[a-z]{2}}/:controller[/]{0,1}",
    [
        "controller" => 2,
        "action"     => "index",
    ]
);
匹配回调函数(Match Callbacks)

Sometimes, routes should only be matched if they meet specific conditions. You can add arbitrary conditions to routes using the beforeMatch() callback. If this function return false, the route will be treated as non-matched:

<?php

$route = $router->add("/login",
    [
        "module"     => "admin",
        "controller" => "session",
    ]
);

$route->beforeMatch(
    function ($uri, $route) {
        // Check if the request was made with Ajax
        if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest") {
            return false;
        }

        return true;
    }
);

You can re-use these extra conditions in classes:

<?php

class AjaxFilter
{
    public function check()
    {
        return $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest";
    }
}

And use this class instead of the anonymous function:

<?php

$route = $router->add(
    "/get/info/{id}",
    [
        "controller" => "products",
        "action"     => "info",
    ]
);

$route->beforeMatch(
    [
        new AjaxFilter(),
        "check"
    ]
);

As of Phalcon 3, there is another way to check this:

<?php

$route = $router->add(
    "/login",
    [
        "module"     => "admin",
        "controller" => "session",
    ]
);

$route->beforeMatch(
    function ($uri, $route) {
        /**
         * @var string $uri
         * @var \Phalcon\Mvc\Router\Route $route
         * @var \Phalcon\DiInterface $this
         * @var \Phalcon\Http\Request $request
         */
        $request = $this->getShared("request");

        // Check if the request was made with Ajax
        return $request->isAjax();
    }
);
限制主机名(Hostname Constraints)

The router allows you to set hostname constraints, this means that specific routes or a group of routes can be restricted to only match if the route also meets the hostname constraint:

<?php

$route = $router->add(
    "/login",
    [
        "module"     => "admin",
        "controller" => "session",
        "action"     => "login",
    ]
);

$route->setHostName("admin.company.com");

The hostname can also be passed as a regular expressions:

<?php

$route = $router->add(
    "/login",
    [
        "module"     => "admin",
        "controller" => "session",
        "action"     => "login",
    ]
);

$route->setHostName("([a-z]+).company.com");

In groups of routes you can set up a hostname constraint that apply for every route in the group:

<?php

use Phalcon\Mvc\Router\Group as RouterGroup;

// Create a group with a common module and controller
$blog = new RouterGroup(
    [
        "module"     => "blog",
        "controller" => "posts",
    ]
);

// Hostname restriction
$blog->setHostName("blog.mycompany.com");

// All the routes start with /blog
$blog->setPrefix("/blog");

// Default route
$blog->add(
    "/",
    [
        "action" => "index",
    ]
);

// Add a route to the group
$blog->add(
    "/save",
    [
        "action" => "save",
    ]
);

// Add another route to the group
$blog->add(
    "/edit/{id}",
    [
        "action" => "edit",
    ]
);

// Add the group to the router
$router->mount($blog);
URI 来源(URI Sources)

By default the URI information is obtained from the $_GET["_url"] variable, this is passed by the Rewrite-Engine to Phalcon, you can also use $_SERVER["REQUEST_URI"] if required:

<?php

use Phalcon\Mvc\Router;

// ...

// Use $_GET["_url"] (default)
$router->setUriSource(
    Router::URI_SOURCE_GET_URL
);

// Use $_SERVER["REQUEST_URI"]
$router->setUriSource(
    Router::URI_SOURCE_SERVER_REQUEST_URI
);

Or you can manually pass a URI to the handle() method:

<?php

$router->handle("/some/route/to/handle");
测试路由(Testing your routes)

Since this component has no dependencies, you can create a file as shown below to test your routes:

<?php

use Phalcon\Mvc\Router;

// These routes simulate real URIs
$testRoutes = [
    "/",
    "/index",
    "/index/index",
    "/index/test",
    "/products",
    "/products/index/",
    "/products/show/101",
];

$router = new Router();

// Add here your custom routes
// ...

// Testing each route
foreach ($testRoutes as $testRoute) {
    // Handle the route
    $router->handle($testRoute);

    echo "Testing ", $testRoute, "<br>";

    // Check if some route was matched
    if ($router->wasMatched()) {
        echo "Controller: ", $router->getControllerName(), "<br>";
        echo "Action: ", $router->getActionName(), "<br>";
    } else {
        echo "The route wasn't matched by any route<br>";
    }

    echo "<br>";
}
注解路由(Annotations Router)

这个组件利用集成的注解服务 annotations 提供了一个路由定义的变体。通过这个策略,你可以直接在书写控制器 的时候编写路由,而不需要一个一个在服务注册的时候添加。

<?php

use Phalcon\Mvc\Router\Annotations as RouterAnnotations;

$di["router"] = function () {
    // Use the annotations router. We're passing false as we don't want the router to add its default patterns
    $router = new RouterAnnotations(false);

    // Read the annotations from ProductsController if the URI starts with /api/products
    $router->addResource("Products", "/api/products");

    return $router;
};

注解通过如下的方式定义:

<?php

/**
 * @RoutePrefix("/api/products")
 */
class ProductsController
{
    /**
     * @Get(
     *     "/"
     * )
     */
    public function indexAction()
    {

    }

    /**
     * @Get(
     *     "/edit/{id:[0-9]+}",
     *     name="edit-robot"
     * )
     */
    public function editAction($id)
    {

    }

    /**
     * @Route(
     *     "/save",
     *     methods={"POST", "PUT"},
     *     name="save-robot"
     * )
     */
    public function saveAction()
    {

    }

    /**
     * @Route(
     *     "/delete/{id:[0-9]+}",
     *     methods="DELETE",
     *     conversors={
     *         id="MyConversors::checkId"
     *     }
     * )
     */
    public function deleteAction($id)
    {

    }

    public function infoAction($id)
    {

    }
}

只有标记了格式正确的注解的方法才能被用作路由。Phalcon支持如下注解:

名称 描述 用法
RoutePrefix A prefix to be prepended to each route URI. This annotation must be placed at the class’ docblock @RoutePrefix("/api/products")
Route This annotation marks a method as a route. This annotation must be placed in a method docblock @Route("/api/products/show")
Get This annotation marks a method as a route restricting the HTTP method to GET @Get("/api/products/search")
Post This annotation marks a method as a route restricting the HTTP method to POST @Post("/api/products/save")
Put This annotation marks a method as a route restricting the HTTP method to PUT @Put("/api/products/save")
Delete This annotation marks a method as a route restricting the HTTP method to DELETE @Delete("/api/products/delete/{id}")
Options This annotation marks a method as a route restricting the HTTP method to OPTIONS @Option("/api/products/info")

用来添加路由的注解支持如下参数:

名称 描述 用法
methods Define one or more HTTP method that route must meet with @Route("/api/products", methods={"GET", "POST"})
name Define a name for the route @Route("/api/products", name="get-products")
paths An array of paths like the one passed to Phalcon\Mvc\Router::add() @Route("/posts/{id}/{slug}", paths={module="backend"})
conversors A hash of conversors to be applied to the parameters @Route("/posts/{id}/{slug}", conversors={id="MyConversor::getId"})

如果路由对应的控制器属于一个模块,使用 addModuleResource() 效果更佳:

<?php

use Phalcon\Mvc\Router\Annotations as RouterAnnotations;

$di["router"] = function () {
    // Use the annotations router
    $router = new RouterAnnotations(false);

    // Read the annotations from Backend\Controllers\ProductsController if the URI starts with /api/products
    $router->addModuleResource("backend", "Products", "/api/products");

    return $router;
};
注册路由实例(Registering Router instance)

You can register router during service registration with Phalcon dependency injector to make it available inside the controllers.

You need to add code below in your bootstrap file (for example index.php or app/config/services.php if you use Phalcon Developer Tools)

<?php

/**
 * Add routing capabilities
 */
$di->set(
    "router",
    function () {
        require __DIR__ . "/../app/config/routes.php";

        return $router;
    }
);

You need to create app/config/routes.php and add router initialization code, for example:

<?php

use Phalcon\Mvc\Router;

$router = new Router();

$router->add(
    "/login",
    [
        "controller" => "login",
        "action"     => "index",
    ]
);

$router->add(
    "/products/:action",
    [
        "controller" => "products",
        "action"     => 1,
    ]
);

return $router;
自定义路由(Implementing your own Router)

The Phalcon\Mvc\RouterInterface interface must be implemented to create your own router replacing the one provided by Phalcon.

调度控制器(Dispatching Controllers)

Phalcon\Mvc\Dispatcher 是MVC应用中负责实例化 控制器和执行在这些控制器上必要动作的组件。理解它的操作和能力将能帮助我们获得更多Phalcon框架提供的服务。

循环调度(The Dispatch Loop)

在MVC流中,这是一个重要的处理环节,特别对于控制器这部分。这些处理 发生在控制调度器中。控制器的文件将会被依次读取、加载和实例化。然后指定的action将会被执行。 如果一个动作将这个流转发给了另一个控制器/动作,控制调度器将会再次启动。为了更好 解释这一点,以下示例怡到好处地说明了在 Phalcon\Mvc\Dispatcher 中的处理过程:

<?php

// 循环调度
while (!$finished) {
    $finished = true;

    $controllerClass = $controllerName . "Controller";

    // 通过自动加载器实例化控制器类
    $controller = new $controllerClass();

    // 执行action
    call_user_func_array(
        [
            $controller,
            $actionName . "Action"
        ],
        $params
    );

    // $finished应该重新加载以检测MVC流
    // 是否转发给了另一个控制器
    $finished = true;
}

上面的代码缺少了验证,过滤器和额外的检查,但它演示了在调度器中正常的操作流。

循环调度事件(Dispatch Loop Events)

Phalcon\Mvc\Dispatcher 可以发送事件给当前的 EventsManager 。 事件会以“dispatch”类型被所触发。当返回false时有些事件可以终止当前激活的操作。已支持的事件如下:

事件名称 何时触发 此操作是否可终止? 触发于
beforeDispatchLoop 在进入循环调度前触发。此时,调度器不知道将要执行的控制器或者动作是否存在。调度器只知道路由传递过来的信息。 侦听者
beforeDispatch 在进入循环调度后触发。此时,调度器不知道将要执行的控制器或者动作是否存在。调度器只知道路由传递过来的信息。 侦听者
beforeExecuteRoute 在执行控制器/动作方法前触发。此时,调度器已经初始化了控制器并知道动作是否存在。 侦听者/控制器
initialize 允许在请求中全局初始化控制器。 控制器
afterExecuteRoute 在执行控制器/动作方法后触发。由于此操作不可终止,所以仅在执行动作后才使用此事件进行清理工作。 侦听者/控制器
beforeNotFoundAction 当控制器中的动作找不到时触发。 侦听者
beforeException 在调度器抛出任意异常前触发。 侦听者
afterDispatch 在执行控制器/动作方法后触发。由于此操作不可终止,所以仅在执行动作后才使用此事件进行清理工作。 侦听者
afterDispatchLoop 在退出循环调度后触发。 侦听者

INVO 这篇导读说明了如何从通过结合 Acl 实现的一个安全过滤器中获得事件调度的好处。

以下例子演示了如何将侦听者绑定到组件上:

<?php

use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 为“dispatch”类型附上一个侦听者
        $eventsManager->attach(
            "dispatch",
            function (Event $event, $dispatcher) {
                // ...
            }
        );

        $dispatcher = new MvcDispatcher();

        // 将$eventsManager绑定到视图组件
        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    },
    true
);

一个实例化的控制器会自动作为事件调度的侦听者,所以你可以实现回调函数:

<?php

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Dispatcher;

class PostsController extends Controller
{
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        // 在每一个找到的动作前执行
    }

    public function afterExecuteRoute(Dispatcher $dispatcher)
    {
        // 在每一个找到的动作后执行
    }
}

注解

Methods on event listeners accept an Phalcon\Events\Event object as their first parameter - methods in controllers do not.

转发到其他动作(Forwarding to other actions)

循环调度允许我们转发执行流到另一个控制器/动作。这对于检查用户是否可以 访问页面,将用户重定向到其他屏幕或简单地代码重用都非常有用。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction($year, $postTitle)
    {
        // ... 储存一些产品并且转发用户

        // 将流转发到index动作
        $this->dispatcher->forward(
            [
                "controller" => "posts",
                "action"     => "index",
            ]
        );
    }
}

请注意制造一个“forward”并不等同于制造一个HTTP的重定向。尽管这两者表面上最终效果都一样。 “forward”不会重新加载当前页面,全部的重定向都只发生在一个请求里面,而HTTP重定向则需要两次请求 才能完成这个流程。

更多转发示例:

<?php

// 将流转发到当前控制器的另一个动作
$this->dispatcher->forward(
    [
        "action" => "search"
    ]
);

// 将流转发到当前控制器的另一个动作
// 传递参数
$this->dispatcher->forward(
    [
        "action" => "search",
        "params" => [1, 2, 3]
    ]
);

一个转发的动作可以接受以下参数:

参数 触发
controller 一个待转发且有效的控制器名字。
action 一个待转发且有效的动作名字。
params 一个传递给动作的数组参数。
namespace 一个控制器对应的命名空间名字。
准备参数(Preparing Parameters)

多得 Phalcon\Mvc\Dispatcher 提供的钩子函数, 你可以简单地 调整你的应用来匹配URL格式:

例如,你想把你的URL看起来像这样:http://example.com/controller/key1/value1/key2/value

默认下,参数会按URL传递的顺序传给对应的动作,你可以按期望来转换他们:

<?php

use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 附上一个侦听者
        $eventsManager->attach(
            "dispatch:beforeDispatchLoop",
            function (Event $event, $dispatcher) {
                $params = $dispatcher->getParams();

                $keyParams = [];

                // 用奇数参数作key,用偶数作值
                foreach ($params as $i => $value) {
                    if ($i & 1) {
                        // Previous param
                        $key = $params[$i - 1];

                        $keyParams[$key] = $value;
                    }
                }

                // 重写参数
                $dispatcher->setParams($keyParams);
            }
        );

        $dispatcher = new MvcDispatcher();

        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);

如果期望的链接是这样: http://example.com/controller/key1:value1/key2:value,那么就需要以下这样的代码:

<?php

use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 附上一个侦听者
        $eventsManager->attach(
            "dispatch:beforeDispatchLoop",
            function (Event $event, $dispatcher) {
                $params = $dispatcher->getParams();

                $keyParams = [];

                // 将每一个参数分解成key、值 对
                foreach ($params as $number => $value) {
                    $parts = explode(":", $value);

                    $keyParams[$parts[0]] = $parts[1];
                }

                // 重写参数
                $dispatcher->setParams($keyParams);
            }
        );

        $dispatcher = new MvcDispatcher();

        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);
获取参数(Getting Parameters)

当路由提供了命名的参数变量,你就可以在控制器、视图或者任何一个继承了 Phalcon\Di\Injectable 的组件中获得这些参数。

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // 从URL传递过来的参数中获取title
        // 或者在一个事件中准备
        $title = $this->dispatcher->getParam("title");

        // 从URL传递过来的参数中获取year
        // 或者在一个事件中准备并且进行过滤
        $year = $this->dispatcher->getParam("year", "int");

        // ...
    }
}
准备行动(Preparing actions)

你也可以为动作定义一个调度前的映射表。

转换动作名(Camelize action names)

如果原始链接是:http://example.com/admin/products/show-latest-products, 例如你想把’show-latest-products’转换成’ShowLatestProducts’, 需要以下代码:

<?php

use Phalcon\Text;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // Camelize动作
        $eventsManager->attach(
            "dispatch:beforeDispatchLoop",
            function (Event $event, $dispatcher) {
                $dispatcher->setActionName(
                    Text::camelize($dispatcher->getActionName())
                );
            }
        );

        $dispatcher = new MvcDispatcher();

        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);
删除遗留的扩展名(Remove legacy extensions)

如果原始链接总是包含一个’.php’扩展名:

http://example.com/admin/products/show-latest-products.php http://example.com/admin/products/index.php

你可以在调度对应的控制器/动作组前将它删除:

<?php

use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 在调度前删除扩展
        $eventsManager->attach(
            "dispatch:beforeDispatchLoop",
            function (Event $event, $dispatcher) {
                $action = $dispatcher->getActionName();

                // 删除扩展
                $action = preg_replace("/\.php$/", "", $action);

                // 重写动作
                $dispatcher->setActionName($action);
            }
        );

        $dispatcher = new MvcDispatcher();

        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);
注入模型实例(Inject model instances)

在这个实例中,开发人员想要观察动作接收到的参数以便可以动态注入模型实例。

控制器看起来像这样:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    /**
     * 显示$post
     *
     * @param \Posts $post
     */
    public function showAction(Posts $post)
    {
        $this->view->post = $post;
    }
}

‘showAction’方法接收到一个 Posts 模型的实例,开发人员可以 在调度动作和准备映射参数前进行观察:

<?php

use Exception;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use ReflectionMethod;

$di->set(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        $eventsManager->attach(
            "dispatch:beforeDispatchLoop",
            function (Event $event, $dispatcher) {
                // 可能的控制器类名
                $controllerName = $dispatcher->getControllerClass();

                // 可能的方法名
                $actionName = $dispatcher->getActiveMethod();

                try {
                    // 从反射中获取将要被执行的方法
                    $reflection = new ReflectionMethod($controllerName, $actionName);

                    $parameters = $reflection->getParameters();


                    // 参数检查
                    foreach ($parameters as $parameter) {
                        // 获取期望的模型名字
                        $className = $parameter->getClass()->name;

                        // 检查参数是否为模型的实例
                        if (is_subclass_of($className, Model::class)) {
                            $model = $className::findFirstById($dispatcher->getParams()[0]);

                            // 根据模型实例重写参数
                            $dispatcher->setParams([$model]);
                        }
                    }
                } catch (Exception $e) {
                    // 异常触发,类或者动作不存在?
                }
            }
        );

        $dispatcher = new MvcDispatcher();

        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);

上面示例出于学术目的已经作了简化。 开发人员可以在执行动作前注入任何类型的依赖或者模型,以进行提高和强化。

From 3.0.x onwards the dispatcher also comes with an option to handle this internally for all models passed into a controller action.

use Phalcon\Mvc\Dispatcher;

$dispatcher = new Dispatcher();

$dispatcher->setModelBinding(true);

return $dispatcher;

It also introduces a new interface Phalcon\Mvc\Controller\BindModelInterface which allows you to define the controllers associated model to allow model binding in base controllers.

For example, you have a base CrudController which your PostsController extends from. Your CrudController looks something like this:

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Model;

class CrudController extends Controller
{
    /**
     * Show action
     *
     * @param Model $model
     */
    public function showAction(Model $model)
    {
        $this->view->model = $model;
    }
}

In your PostsController you need to define which model the controller is associated with. This is done by implementing the Phalcon\Mvc\Controller\BindModelInterface which will add the getModelName() method from which you can return the model name.

use Phalcon\Mvc\Controller\BindModelInterface;
use Models\Posts;

class PostsController extends CrudController implements BindModelInterface
{
    public static function getModelName()
    {
        return Posts::class;
    }
}

By declaring the model associated with the PostsController the dispatcher can check the controller for the getModelName() method before passing the defined model into the parent show action.

If your project structure does not use any parent controller you can of course still bind the model directly into the controller action:

use Phalcon\Mvc\Controller;
use Models\Posts;

class PostsController extends Controller
{
    /**
     * Shows posts
     *
     * @param Posts $post
     */
    public function showAction(Posts $post)
    {
        $this->view->post = $post;
    }
}
Currently the dispatchers internal model binding will only use the models primary key to perform a findFirst() on. An example route for the above would be /posts/show/{1}
处理 Not-Found 错误(Handling Not-Found Exceptions)

使用 EventsManager ,可以在调度器找不到对应的控制器/动作组时而抛出异常前,插入一个钩子:

<?php

use Exception;
use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Mvc\Dispatcher\Exception as DispatchException;

$di->setShared(
    "dispatcher",
    function () {
        // 创建一个事件管理
        $eventsManager = new EventsManager();

        // 附上一个侦听者
        $eventsManager->attach(
            "dispatch:beforeException",
            function (Event $event, $dispatcher, Exception $exception) {
                // 处理404异常
                if ($exception instanceof DispatchException) {
                    $dispatcher->forward(
                        [
                            "controller" => "index",
                            "action"     => "show404",
                        ]
                    );

                    return false;
                }

                // 代替控制器或者动作不存在时的路径
                switch ($exception->getCode()) {
                    case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                    case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                        $dispatcher->forward(
                            [
                                "controller" => "index",
                                "action"     => "show404",
                            ]
                        );

                        return false;
                }
            }
        );

        $dispatcher = new MvcDispatcher();

        // 将EventsManager绑定到调度器
        $dispatcher->setEventsManager($eventsManager);

        return $dispatcher;
    }
);

当然,这个方法也可以移至独立的插件类中,使得在循环调度产生异常时可以有超过一个类执行需要的动作:

<?php

use Exception;
use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Dispatcher\Exception as DispatchException;

class ExceptionsPlugin
{
    public function beforeException(Event $event, Dispatcher $dispatcher, Exception $exception)
    {
        // Default error action
        $action = "show503";

        // 处理404异常
        if ($exception instanceof DispatchException) {
            $action = "show404";
        }

        $dispatcher->forward(
            [
                "controller" => "index",
                "action"     => $action,
            ]
        );

        return false;
    }
}
仅仅当异常产生于调度器或者异常产生于被执行的动作时才会通知’beforeException’里面的事件。 侦听者或者控制器事件中产生的异常则会重定向到最近的try/catch。
自定义调度器(Implementing your own Dispatcher)

为了创建自定义调度器,必须实现 Phalcon\Mvc\DispatcherInterface 接口, 从而替换Phalcon框架默认提供的调度器。

Micro Applications

使用Phalcon框架开发者可以创建微框架应用。 这样开发者只需要书写极少的代码即可创建一个PHP应用。 微应用适用于书写小的应用, API或原型等

<?php

use Phalcon\Mvc\Micro;

$app = new Micro();

$app->get(
    "/say/welcome/{name}",
    function ($name) {
        echo "<h1>Welcome $name!</h1>";
    }
);

$app->handle();
创建微应用(Creating a Micro Application)

Phalcon中 使用 Phalcon\Mvc\Micro 来实现微应用。

<?php

use Phalcon\Mvc\Micro;

$app = new Micro();
定义路由(Defining routes)

实例化后, 开发者需要添加一些路由规则。 Phalcon内部使用 Phalcon\Mvc\Router 来管理路由。 路由必须以 / 开头。 定义路由时通常会书写http方法约束, 这样路由规则只适用于那些和规则及htttp方法相匹配的路由。 下面的方法展示了如何定义了HTTP get方法路由:

<?php

$app->get(
    "/say/hello/{name}",
    function ($name) {
        echo "<h1>Hello! $name</h1>";
    }
);

get 方法指定了要匹配的请求方法。 路由规则 /say/hello/{name} 中含有一个参数 {$name}, 此参数会直接传递给路由的处理器(此处为匿名函数)。 路由规则匹配时处理器即会执行。 处理器是PHP中任何可以被调用的项。 下面的示例中展示了如何定义不同种类的处理器:

<?php

//  函数
function say_hello($name) {
    echo "<h1>Hello! $name</h1>";
}

$app->get(
    "/say/hello/{name}",
    "say_hello"
);

//  静态方法
$app->get(
    "/say/hello/{name}",
    "SomeClass::someSayMethod"
);

//  对象内的方法
$myController = new MyController();
$app->get(
    "/say/hello/{name}",
    [
        $myController,
        "someAction"
    ]
);

// 匿名函数
$app->get(
    "/say/hello/{name}",
    function ($name) {
        echo "<h1>Hello! $name</h1>";
    }
);

Phalcon\Mvc\Micro 提供了一系列的用于定义http方法的限定方法:

<?php

// 匹配HTTP GET 方法:
$app->get(
    "/api/products",
    "get_products"
);

// 匹配HTTP POST方法
$app->post(
    "/api/products/add",
    "add_product"
);

// 匹配HTTP PUT 方法
$app->put(
    "/api/products/update/{id}",
    "update_product"
);

// 匹配HTTP DELETE方法
$app->delete(
    "/api/products/remove/{id}",
    "delete_product"
);

// 匹配HTTP OPTIONS方法
$app->options(
    "/api/products/info/{id}",
    "info_product"
);

// 匹配HTTP PATCH方法
$app->patch(
    "/api/products/update/{id}",
    "info_product"
);

// 匹配HTTP GET 或 POST方法
$app->map(
    "/repos/store/refs",
    "action_product"
)->via(
    [
        "GET",
        "POST",
    ]
);

To access the HTTP method data $app needs to be passed into the closure:

<?php

// Matches if the HTTP method is POST
$app->post(
    "/api/products/add",
    function () use ($app) {
        echo $app->request->getPost("productID");
    }
);
路由参数(Routes with Parameters)

如上面的例子中展示的那样在路由中定义参数是非常容易的。 参数名需要放在花括号内。 参数格式亦可使用正则表达式以确保数据一致性。 例子如下:

<?php

// 此路由有两个参数每个参数有一格式
$app->get(
    "/posts/{year:[0-9]+}/{title:[a-zA-Z\-]+}",
    function ($year, $title) {
        echo "<h1>Title: $title</h1>";
        echo "<h2>Year: $year</h2>";
    }
);
起始路由(Starting Route)

通常情况下, 应用一般由 / 路径开始访问, 当然此访问多为 GET方法。 这种情况代码如下:

<?php

// 超始路由
$app->get(
    "/",
    function () {
        echo "<h1>Welcome!</h1>";
    }
);
重写规则(Rewrite Rules)

下面的规则用来实现apache重写:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
</IfModule>
处理响应(Working with Responses)

开发者可以在路由处理器中设置任务种类的响应:直接输出, 使用模板引擎, 包含视图, 返回json数据等。

<?php

// 直接输出
$app->get(
    "/say/hello",
    function () {
        echo "<h1>Hello! $name</h1>";
    }
);

// 包含其它文件
$app->get(
    "/show/results",
    function () {
        require "views/results.php";
    }
);

// 返回JSON
$app->get(
    "/get/some-json",
    function () {
        echo json_encode(
            [
                "some",
                "important",
                "data",
            ]
        );
    }
);

另外开发者还可以使用 “response” , 这样开发者可以更好的处理结果:

<?php

$app->get(
    "/show/data",
    function () use ($app) {
        // 设置返回头部内容格式
        $app->response->setContentType("text/plain");

        $app->response->sendHeaders();

        // 输出文件内容
        readfile("data.txt");
    }
);

或回复response对象:

<?php

$app->get(
    "/show/data",
    function () {
        // 创建Response类实例
        $response = new Phalcon\Http\Response();

        // Set the Content-Type header 设置返回内容的类型
        $response->setContentType("text/plain");

        // 设置文件内容参数
        $response->setContent(file_get_contents("data.txt"));

        // 返回response实例对象
        return $response;
    }
);
重定向(Making redirections)

重定向用来在当前的处理中跳转到其它的处理流:

<?php

// 此路由重定向到其它的路由
$app->post("/old/welcome",
    function () use ($app) {
        $app->response->redirect("new/welcome");

        $app->response->sendHeaders();
    }
);

$app->post("/new/welcome",
    function () use ($app) {
        echo "This is the new Welcome";
    }
);
根据路由生成 URL(Generating URLs for Routes)

Phalcon中使用 Phalcon\Mvc\Url 来生成其它的基于路由的URL。 开发者可以为路由设置名字, 通过这种方式 “url” 服务可以产生相关的路由:

<?php

// 设置名为 "show-post"的路由
$app->get(
    "/blog/{year}/{title}",
    function ($year, $title) use ($app) {
        // ... Show the post here
    }
)->setName("show-post");

// 产生URL
$app->get(
    "/",
    function () use ($app) {
        echo '<a href="', $app->url->get(
            [
                "for"   => "show-post",
                "title" => "php-is-a-great-framework",
                "year"  => 2015
            ]
        ), '">Show the post</a>';
    }
);
与依赖注入的交互(Interacting with the Dependency Injector)

微应用中, Phalcon\Di\FactoryDefault 是隐含生成的, 不过开发者可以明确的生成此类的实例以用来管理相关的服务:

<?php

use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Config\Adapter\Ini as IniConfig;

$di = new FactoryDefault();

$di->set(
    "config",
    function () {
        return new IniConfig("config.ini");
    }
);

$app = new Micro();

$app->setDI($di);

$app->get(
    "/",
    function () use ($app) {
        // Read a setting from the config
        echo $app->config->app_name;
    }
);

$app->post(
    "/contact",
    function () use ($app) {
        $app->flash->success("Yes!, the contact was made!");
    }
);

服务容器中可以使用数据类的语法来设置或取服务实例:

<?php

use Phalcon\Mvc\Micro;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlAdapter;

$app = new Micro();

// 设置数据库服务实例
$app["db"] = function () {
    return new MysqlAdapter(
        [
            "host"     => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname"   => "test_db"
        ]
    );
};

$app->get(
    "/blog",
    function () use ($app) {
        $news = $app["db"]->query("SELECT * FROM news");

        foreach ($news as $new) {
            echo $new->title;
        }
    }
);
处理Not-Found(Not-Found Handler)

当用户访问未定义的路由时, 微应用会试着执行 “Not-Found”处理器。 示例如下:

<?php

$app->notFound(
    function () use ($app) {
        $app->response->setStatusCode(404, "Not Found");

        $app->response->sendHeaders();

        echo "This is crazy, but this page was not found!";
    }
);
微应用中的模型(Models in Micro Applications)

Phalcon中开发者可以直接使用 Models , 开发者只需要一个类自动加载器来加载模型:

<?php

$loader = new \Phalcon\Loader();

$loader->registerDirs(
    [
        __DIR__ . "/models/"
    ]
)->register();

$app = new \Phalcon\Mvc\Micro();

$app->get(
    "/products/find",
    function () {
        $products = Products::find();

        foreach ($products as $product) {
            echo $product->name, "<br>";
        }
    }
);

$app->handle();
微应用中的事件(Micro Application Events)

当有事件发生时 Phalcon\Mvc\Micro 会发送事件到 EventsManager 。 这里使用 “micro” 来绑定处理事件。 支持如下事件:

事件名 如何触发 是否可中断执行
beforeHandleRoute 处理方法调用之前执行, 此时应用程序还不知道是否存在匹配的路由
beforeExecuteRoute 存在匹配的路由及相关的处理器, 不过处理器还未被执行
afterExecuteRoute 处理器执行之后触发
beforeNotFound NotFound触发之前执行
afterHandleRoute 处理器执行之后执行

下面的例子中, 我们阐述了如何使用事件来控制应用的安全性:

<?php

use Phalcon\Mvc\Micro;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

// 创建事件监听器
$eventsManager = new EventsManager();

$eventsManager->attach(
    "micro:beforeExecuteRoute",
    function (Event $event, $app) {
        if ($app->session->get("auth") === false) {
            $app->flashSession->error("The user isn't authenticated");

            $app->response->redirect("/");

            $app->response->sendHeaders();

            // 返回false来中止操作
            return false;
        }
    }
);

$app = new Micro();

// 绑定事件管理器到应用
$app->setEventsManager($eventsManager);
中间件事件(Middleware events)

此外, 应用事件亦可使用 ‘before’, ‘after’, ‘finish’等来绑定:

<?php

$app = new Phalcon\Mvc\Micro();

// 每个路由匹配之前执行
// 返回false来中止程序执行
$app->before(
    function () use ($app) {
        if ($app["session"]->get("auth") === false) {
            $app["flashSession"]->error("The user isn't authenticated");

            $app["response"]->redirect("/error");

            // Return false stops the normal execution
            return false;
        }

        return true;
    }
);

$app->map(
    "/api/robots",
    function () {
        return [
            "status" => "OK",
        ];
    }
);

$app->after(
    function () use ($app) {
        // 路由处理器执行后执行
        echo json_encode($app->getReturnedValue());
    }
);

$app->finish(
    function () use ($app) {
        // 路由处理器执行后执行
    }
);

开发者可以对同一事件注册多个处理器:

<?php

$app->finish(
    function () use ($app) {
        // 第一个结束处理器
    }
);

$app->finish(
    function () use ($app) {
        // 第二个结束处理器
    }
);

把这些代码放在另外的文件中以达到重用的目的:

<?php

use Phalcon\Mvc\Micro\MiddlewareInterface;

/**
 * CacheMiddleware
 *
 * 使用缓存来提升性能
 */
class CacheMiddleware implements MiddlewareInterface
{
    public function call($application)
    {
        $cache  = $application["cache"];
        $router = $application["router"];

        $key = preg_replace("/^[a-zA-Z0-9]/", "", $router->getRewriteUri());

        // 检查请示是否被处理了
        if ($cache->exists($key)) {
            echo $cache->get($key);

            return false;
        }

        return true;
    }
}

添加实例到应用:

<?php

$app->before(
    new CacheMiddleware()
);

支持如下的中间件事件:

事件名 触发 是否可中止操作?
before 应用请求处理之前执行,常用来控制应用的访问权限 Yes
after 请求处理后执行,可以用来准备回复内容 No
finish 发送回复内容后执行, 可以用来执行清理工作 No
使用控制器处理(Using Controllers as Handlers)

中型的应用可以使用 Mvc\Micro 来组织控制器中的处理器。 开发者也可以使用 Phalcon\Mvc\Micro\Collection 来对控制器中的处理器进行归组:

<?php

use Phalcon\Mvc\Micro\Collection as MicroCollection;

$posts = new MicroCollection();

// 设置主处理器,这里是控制器的实例
$posts->setHandler(
    new PostsController()
);

// 对所有路由设置前缀
$posts->setPrefix("/posts");

//  使用PostsController中的index action
$posts->get("/", "index");

// 使用PostController中的show action
$posts->get("/show/{slug}", "show");

$app->mount($posts);

PostsController形如下:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function index()
    {
        // ...
    }

    public function show($slug)
    {
        // ...
    }
}

上面的例子中,我们直接对控制器进行了实例化, 使用集合时Phalcon会提供了迟加载的能力, 这样程序只有在匹配路由时才加载控制器:

<?php

$posts->setHandler('PostsController', true);
$posts->setHandler('Blog\Controllers\PostsController', true);
返回响应(Returning Responses)

处理器可能会返回原生的 Phalcon\Http\Response 实例或实现了相关接口的组件。 当返回Response对象时, 应用会自动的把处理结果返回到客户端。

<?php

use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;

$app = new Micro();

// 返回Response实例
$app->get(
    "/welcome/index",
    function () {
        $response = new Response();

        $response->setStatusCode(401, "Unauthorized");

        $response->setContent("Access is not authorized");

        return $response;
    }
);
渲染视图(Rendering Views)

Phalcon\Mvc\View\Simple 可用来渲染视图, 示例如下:

<?php

$app = new Phalcon\Mvc\Micro();

$app["view"] = function () {
    $view = new \Phalcon\Mvc\View\Simple();

    $view->setViewsDir("app/views/");

    return $view;
};

// 返回渲染过的视图
$app->get(
    "/products/show",
    function () use ($app) {
        // 渲染视图时传递参数
        echo $app["view"]->render(
            "products/show",
            [
                "id"   => 100,
                "name" => "Artichoke"
            ]
        );
    }
);

Please note that this code block uses Phalcon\Mvc\View\Simple which uses relative paths instead of controllers and actions. If you would like to use Phalcon\Mvc\View\Simple instead, you will need to change the parameters of the render() method:

<?php

$app = new Phalcon\Mvc\Micro();

$app["view"] = function () {
    $view = new \Phalcon\Mvc\View();

    $view->setViewsDir("app/views/");

    return $view;
};

// Return a rendered view
$app->get(
    "/products/show",
    function () use ($app) {
        // Render app/views/products/show.phtml passing some variables
        echo $app["view"]->render(
            "products",
            "show",
            [
                "id"   => 100,
                "name" => "Artichoke"
            ]
        );
    }
);
Error Handling

A proper response can be generated if an exception is raised in a micro handler:

<?php

$app = new Phalcon\Mvc\Micro();

$app->get(
    "/",
    function () {
        throw new \Exception("An error");
    }
);

$app->error(
    function ($exception) {
        echo "An error has occurred";
    }
);

If the handler returns “false” the exception is stopped.

使用命名空间(Working with Namespaces)

Namespaces 可以用来避免类名的冲突,比如如果在一个应用中有两个控制器使用同样的名称,那么可以用namespace来区分他们。 另外命名空间在创建组件或者模块的时候也是非常有用的。

设置框架(Setting up the framework)

Using namespaces has some implications when loading the appropriate controller. To adjust the framework behavior to namespaces is necessary to perform one or all of the following tasks:

Use an autoload strategy that takes into account the namespaces, for example with Phalcon\Loader:

<?php

$loader->registerNamespaces(
    [
       "Store\\Admin\\Controllers" => "../bundles/admin/controllers/",
       "Store\\Admin\\Models"      => "../bundles/admin/models/",
    ]
);

Specify it in the routes as a separate parameter in the route’s paths:

<?php

$router->add(
    "/admin/users/my-profile",
    [
        "namespace"  => "Store\\Admin",
        "controller" => "Users",
        "action"     => "profile",
    ]
);

Passing it as part of the route:

<?php

$router->add(
    "/:namespace/admin/users/my-profile",
    [
        "namespace"  => 1,
        "controller" => "Users",
        "action"     => "profile",
    ]
);

If you are only working with the same namespace for every controller in your application, then you can define a default namespace in the Dispatcher, by doing this, you don’t need to specify a full class name in the router path:

<?php

use Phalcon\Mvc\Dispatcher;

// Registering a dispatcher
$di->set(
    "dispatcher",
    function () {
        $dispatcher = new Dispatcher();

        $dispatcher->setDefaultNamespace(
            "Store\\Admin\\Controllers"
        );

        return $dispatcher;
    }
);
控制器加入命名空间(Controllers in Namespaces)

The following example shows how to implement a controller that use namespaces:

<?php

namespace Store\Admin\Controllers;

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function indexAction()
    {

    }

    public function profileAction()
    {

    }
}
模型加入命名空间(Models in Namespaces)

Take the following into consideration when using models in namespaces:

<?php

namespace Store\Models;

use Phalcon\Mvc\Model;

class Robots extends Model
{

}

If models have relationships they must include the namespace too:

<?php

namespace Store\Models;

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->hasMany(
            "id",
            "Store\\Models\\Parts",
            "robots_id",
            [
                "alias" => "parts",
            ]
        );
    }
}

In PHQL you must write the statements including namespaces:

<?php

$phql = "SELECT r.* FROM Store\Models\Robots r JOIN Store\Models\Parts p";

事件管理器(Events Manager)

此组件的目的是为了通过创建“钩子”拦截框架中大部分的组件操作。 这些钩子允许开发者获得状态信息,操纵数据或者改变某个组件进程中的执行流向。

Naming Convention

Phalcon events use namespaces to avoid naming collisions. Each component in Phalcon occupies a different event namespace and you are free to create your own as you see fit. Event names are formatted as “component:event”. For example, as Phalcon\Db occupies the “db” namespace, its “afterQuery” event’s full name is “db:afterQuery”.

When attaching event listeners to the events manager, you can use “component” to catch all events from that component (eg. “db” to catch all of the Phalcon\Db events) or “component:event” to target a specific event (eg. “db:afterQuery”).

使用示例(Usage Example)

In the following example, we will use the EventsManager to listen for the “afterQuery” event produced in a MySQL connection managed by Phalcon\Db:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;

$eventsManager = new EventsManager();

$eventsManager->attach(
    "db:afterQuery",
    function (Event $event, $connection) {
        echo $connection->getSQLStatement();
    }
);

$connection = new DbAdapter(
    [
        "host"     => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname"   => "invo",
    ]
);

// 将$eventsManager赋值给数据库甜适配器
$connection->setEventsManager($eventsManager);

// 发送一个SQL命令到数据库服务器
$connection->query(
    "SELECT * FROM products p WHERE p.status = 1"
);

Now every time a query is executed, the SQL statement will be echoed out. 第一个传递给事件侦听者的参数包含了关于正在运行事件的上下文信息,第二个则是连接本身。 A third parameter may also be specified which will contain arbitrary data specific to the event.

You must explicitly set the Events Manager to a component using the setEventsManager() method in order for that component to trigger events. You can create a new Events Manager instance for each component or you can set the same Events Manager to multiple components as the naming convention will avoid conflicts.

Instead of using lambda functions, you can use event listener classes instead. Event listeners also allow you to listen to multiple events. 作为些示例的一部分,我们同样实现了 Phalcon\Db\Profiler 来检测SQL语句是否超出了期望的执行时间:

<?php

use Phalcon\Db\Profiler;
use Phalcon\Events\Event;
use Phalcon\Logger;
use Phalcon\Logger\Adapter\File;

class MyDbListener
{
    protected $_profiler;

    protected $_logger;

    /**
     *创建分析器并开始纪录
     */
    public function __construct()
    {
        $this->_profiler = new Profiler();
        $this->_logger   = new Logger("../apps/logs/db.log");
    }

    /**
     * 如果事件触发器是'beforeQuery',此函数将会被执行
     */
    public function beforeQuery(Event $event, $connection)
    {
        $this->_profiler->startProfile(
            $connection->getSQLStatement()
        );
    }

    /**
     * 如果事件触发器是'afterQuery',此函数将会被执行
     */
    public function afterQuery(Event $event, $connection)
    {
        $this->_logger->log(
            $connection->getSQLStatement(),
            Logger::INFO
        );

        $this->_profiler->stopProfile();
    }

    public function getProfiler()
    {
        return $this->_profiler;
    }
}

Attaching an event listener to the events manager is as simple as:

<?php

// 创建一个数据库侦听
$dbListener = new MyDbListener();

// 侦听全部数据库事件
$eventsManager->attach(
    "db",
    $dbListener
);

可以从侦听者中获取结果分析数据:

<?php

// 发送一个SQL命令到数据库服务器
$connection->execute(
    "SELECT * FROM products p WHERE p.status = 1"
);

foreach ($dbListener->getProfiler()->getProfiles() as $profile) {
    echo "SQL语句: ", $profile->getSQLStatement(), "\n";
    echo "开始时间: ", $profile->getInitialTime(), "\n";
    echo "结束时间: ", $profile->getFinalTime(), "\n";
    echo "总共执行的时间: ", $profile->getTotalElapsedSeconds(), "\n";
}
创建组件触发事件(Creating components that trigger Events)

你可以在你的应用中为事件管理器的触发事件创建组件。这样的结果是,可以有很多存在的侦听者为这些产生的事件作出响应。 在以下的示例中,我们将会创建一个叫做“MyComponent”组件。这是个意识事件管理器组件; 当它的方法:code:`someTask()`被执行时它将触发事件管理器中全部侦听者的两个事件:

<?php

use Phalcon\Events\EventsAwareInterface;
use Phalcon\Events\Manager as EventsManager;

class MyComponent implements EventsAwareInterface
{
    protected $_eventsManager;

    public function setEventsManager(EventsManager $eventsManager)
    {
        $this->_eventsManager = $eventsManager;
    }

    public function getEventsManager()
    {
        return $this->_eventsManager;
    }

    public function someTask()
    {
        $this->_eventsManager->fire("my-component:beforeSomeTask", $this);

        // 做一些你想做的事情
        echo "这里, someTask\n";

        $this->_eventsManager->fire("my-component:afterSomeTask", $this);
    }
}

Notice that in this example, we’re using the “my-component” event namespace. 现在让我们来为这个组件创建一个侦听者:

<?php

use Phalcon\Events\Event;

class SomeListener
{
    public function beforeSomeTask(Event $event, $myComponent)
    {
        echo "这里, beforeSomeTask\n";
    }

    public function afterSomeTask(Event $event, $myComponent)
    {
        echo "这里, afterSomeTask\n";
    }
}

现在让我们把全部的东西整合起来:

<?php

use Phalcon\Events\Manager as EventsManager;

// 创建一个事件管理器
$eventsManager = new EventsManager();

// 创建MyComponent实例
$myComponent = new MyComponent();

// 将事件管理器绑定到创建MyComponent实例实例
$myComponent->setEventsManager($eventsManager);

// 为事件管理器附上侦听者
$eventsManager->attach(
    "my-component",
    new SomeListener()
);

// 执行组件的方法
$myComponent->someTask();

当:code:`someTask()`被执行时,在侦听者里面的两个方法将会被执行,并产生以下输出:

这里, beforeSomeTask
这里, someTask
这里, afterSomeTask

当触发一个事件时也可以使用:code:`fire()`中的第三个参数来传递额外的数据:

<?php

$eventsManager->fire("my-component:afterSomeTask", $this, $extraData);

在一个侦听者里,第三个参数可用于接收此参数:

<?php

use Phalcon\Events\Event;

// 从第三个参数接收数据
$eventsManager->attach(
    "my-component",
    function (Event $event, $component, $data) {
        print_r($data);
    }
);

// 从事件上下文中接收数据
$eventsManager->attach(
    "my-component",
    function (Event $event, $component) {
        print_r($event->getData());
    }
);
Using Services From The DI

By extending Phalcon\Mvc\User\Plugin, you can access services from the DI, just like you would in a controller:

<?php

use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;

class SomeListener extends Plugin
{
    public function beforeSomeTask(Event $event, $myComponent)
    {
        echo "Here, beforeSomeTask\n";

        $this->logger->debug(
            "beforeSomeTask has been triggered";
        );
    }

    public function afterSomeTask(Event $event, $myComponent)
    {
        echo "Here, afterSomeTask\n";

        $this->logger->debug(
            "afterSomeTask has been triggered";
        );
    }
}
事件传播与取消(Event Propagation/Cancellation)

可能会有多个侦听者添加到同一个事件管理器,这意味着对于相同的事件会通知多个侦听者。 这些侦听者会以它们在事件管理器注册的顺序来通知。有些事件是可以被取消的,暗示着这些事件可以被终止以防其他侦听都再收到事件的通知:

<?php

use Phalcon\Events\Event;

$eventsManager->attach(
    "db",
    function (Event $event, $connection) {
        // 如果可以取消,我们就终止此事件
        if ($event->isCancelable()) {
            // 终止事件,这样的话其他侦听都就不会再收到此通知
            $event->stop();
        }

        // ...
    }
);

默认情况下全部的事件都是可以取消的,甚至框架提供的事件也是可以取消的。 你可以通过在 fire() 中的第四个参数中传递 false 来指明这是一个不可取消的事件:

<?php

$eventsManager->fire("my-component:afterSomeTask", $this, $extraData, false);
侦听器优先级(Listener Priorities)

当附上侦听者时,你可以设置一个优先级。使用此特性,你可以指定这些侦听者被调用的固定顺序:

<?php

$eventsManager->enablePriorities(true);

$eventsManager->attach("db", new DbListener(), 150); // 高优先级
$eventsManager->attach("db", new DbListener(), 100); // 正常优先级
$eventsManager->attach("db", new DbListener(), 50);  // 低优先级
收集响应(Collecting Responses)

事件管理器可以收集每一个被通知的侦听者返回的响应,以下这个示例解释了它是如何工作的:

<?php

use Phalcon\Events\Manager as EventsManager;

$eventsManager = new EventsManager();

// 建立事件管理器以为收集结果响应
$eventsManager->collectResponses(true);

// 附上一个侦听者
$eventsManager->attach(
    "custom:custom",
    function () {
        return "first response";
    }
);

// 附上一个侦听者
$eventsManager->attach(
    "custom:custom",
    function () {
        return "second response";
    }
);

// 执行fire事件
$eventsManager->fire("custom:custom", null);

// 获取全部收集到的响应
print_r($eventsManager->getResponses());

上面示例将输出:

Array ( [0] => first response [1] => second response )
自定义事件管理器(Implementing your own EventsManager)

如果想要替换Phalcon提供的事件管理器,必须实现 Phalcon\Events\ManagerInterface 中的接口。

Request Environment

Every HTTP request (usually originated by a browser) contains additional information regarding the request such as header data, files, variables, etc. A web based application needs to parse that information so as to provide the correct response back to the requester. Phalcon\Http\Request encapsulates the information of the request, allowing you to access it in an object-oriented way.

<?php

use Phalcon\Http\Request;

// Getting a request instance
$request = new Request();

// Check whether the request was made with method POST
if ($request->isPost()) {
    // Check whether the request was made with Ajax
    if ($request->isAjax()) {
        echo "Request was made using POST and AJAX";
    }
}
获取值(Getting Values)

PHP automatically fills the superglobal arrays $_GET and $_POST 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 $_REQUEST, $_GET and $_POST arrays and sanitize or filter them with the ‘filter’ service, (by default Phalcon\Filter). The following examples offer the same behavior:

<?php

use Phalcon\Filter;

$filter = new Filter();

// Manually applying the filter
$email = $filter->sanitize($_POST["user_email"], "email");

// Manually applying the filter to the value
$email = $filter->sanitize($request->getPost("user_email"), "email");

// Automatically applying the filter
$email = $request->getPost("user_email", "email");

// Setting a default value if the param is null
$email = $request->getPost("user_email", "email", "some@example.com");

// Setting a default value if the param is null without filtering
$email = $request->getPost("user_email", null, "some@example.com");
控制器中访问请求(Accessing the Request from Controllers)

The most common place to access the request environment is in an action of a controller. To access the Phalcon\Http\Request object from a controller you will need to use the $this->request public property of the controller:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // Check if request has made with POST
        if ($this->request->isPost()) {
            // Access POST data
            $customerName = $this->request->getPost("name");
            $customerBorn = $this->request->getPost("born");
        }
    }
}
文件上传(Uploading Files)

Another common task is file uploading. Phalcon\Http\Request offers an object-oriented way to achieve this task:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function uploadAction()
    {
        // Check if the user has uploaded files
        if ($this->request->hasFiles()) {
            $files = $this->request->getUploadedFiles();

            // Print the real file names and sizes
            foreach ($files as $file) {
                // Print file details
                echo $file->getName(), " ", $file->getSize(), "\n";

                // Move the file into the application
                $file->moveTo(
                    "files/" . $file->getName()
                );
            }
        }
    }
}

Each object returned by Phalcon\Http\Request::getUploadedFiles() is an instance of the Phalcon\Http\Request\File class. Using the $_FILES superglobal array offers the same behavior. Phalcon\Http\Request\File encapsulates only the information related to each file uploaded with the request.

使用头信息(Working with Headers)

As mentioned above, request headers contain useful information that allow us to send the proper response back to the user. The following examples show usages of that information:

<?php

// Get the Http-X-Requested-With header
$requestedWith = $request->getHeader("HTTP_X_REQUESTED_WITH");

if ($requestedWith === "XMLHttpRequest") {
    echo "The request was made with Ajax";
}

// Same as above
if ($request->isAjax()) {
    echo "The request was made with Ajax";
}

// Check the request layer
if ($request->isSecure()) {
    echo "The request was made using a secure layer";
}

// Get the servers's IP address. ie. 192.168.0.100
$ipAddress = $request->getServerAddress();

// Get the client's IP address ie. 201.245.53.51
$ipAddress = $request->getClientAddress();

// Get the User Agent (HTTP_USER_AGENT)
$userAgent = $request->getUserAgent();

// Get the best acceptable content by the browser. ie text/xml
$contentType = $request->getAcceptableContent();

// Get the best charset accepted by the browser. ie. utf-8
$charset = $request->getBestCharset();

// Get the best language accepted configured in the browser. ie. en-us
$language = $request->getBestLanguage();

返回响应(Returning Responses)

Phalcon\Http\Response 是Phalcon中用来处理HTTP响应返回的组件。 HTTP响应通常是由响应头和响应体组成的。下面是一些基本用法:

<?php

use Phalcon\Http\Response;

// 获取一个响应实例
$response = new Response();

// 设置HTTP状态码
$response->setStatusCode(404, "Not Found");

// 设置响应内容
$response->setContent("Sorry, the page doesn't exist");

// 返回响应到客户端
$response->send();

If you are using the full MVC stack there is no need to create responses manually. However, if you need to return a response directly from a controller’s action follow this example:

<?php

use Phalcon\Http\Response;
use Phalcon\Mvc\Controller;

class FeedController extends Controller
{
    public function getAction()
    {
        // Getting a response instance
        $response = new Response();

        $feed = // ... Load here the feed

        // Set the content of the response
        $response->setContent(
            $feed->asString()
        );

        // Return the response
        return $response;
    }
}
使用头部信息(Working with Headers)

在HTTP响应返回中,响应头(Headers)是非常重要的组成部分. 它包含了一些非常有用的信息,比如HTTP状态码,响应类型等等.

你可以使用如下方式来设置头信息:

<?php

// Setting a header by its name
$response->setHeader("Content-Type", "application/pdf");
$response->setHeader("Content-Disposition", 'attachment; filename="downloaded.pdf"');

// Setting a raw header
$response->setRawHeader("HTTP/1.1 200 OK");

A Phalcon\Http\Response\Headers bag internally manages headers. This class retrieves the headers before sending it to client:

<?php

// Get the headers bag
$headers = $response->getHeaders();

// Get a header by its name
$contentType = $headers->get("Content-Type");
重定向(Making Redirections)

可以通过 Phalcon\Http\Response 来执行HTTP重定向:

<?php

// Redirect to the default URI
$response->redirect();

// Redirect to the local base URI
$response->redirect("posts/index");

// Redirect to an external URL
$response->redirect("http://en.wikipedia.org", true);

// Redirect specifying the HTTP status code
$response->redirect("http://www.example.com/new-location", true, 301);

All internal URIs are generated using the ‘url’ service (by default Phalcon\Mvc\Url). This example demonstrates how you can redirect using a route you have defined in your application:

所有内部 URIs 都是通过 ‘url’ 来生成的( 默认是 Phalcon\Mvc\Url )。下面的例子演示如何通过一个应用内预先定义好的路由来重定向。

<?php

// Redirect based on a named route
return $response->redirect(
    [
        "for"        => "index-lang",
        "lang"       => "jp",
        "controller" => "index",
    ]
);

Note that a redirection doesn’t disable the view component, so if there is a view associated with the current action it will be executed anyway. You can disable the view from a controller by executing $this->view->disable();

值得注意的是重定向并不禁用view组件,所以如果当前的action存在一个关联的view的话,将会继续执行它。在控制器中可以通过 $this->view->disable() 来禁用view。

HTTP 缓存(HTTP Cache)

One of the easiest ways to improve the performance in your applications and reduce the traffic is using HTTP Cache. Most modern browsers support HTTP caching and is one of the reasons why many websites are currently fast.

HTTP Cache can be altered in the following header values sent by the application when serving a page for the first time:

  • Expires: With this header the application can set a date in the future or the past telling the browser when the page must expire.
  • Cache-Control: This header allows to specify how much time a page should be considered fresh in the browser.
  • Last-Modified: This header tells the browser which was the last time the site was updated avoiding page re-loads
  • ETag: An etag is a unique identifier that must be created including the modification timestamp of the current page
设置过期时间(Setting an Expiration Time)

The expiration date is one of the easiest and most effective ways to cache a page in the client (browser). Starting from the current date we add the amount of time the page will be stored in the browser cache. Until this date expires no new content will be requested from the server:

<?php

$expiryDate = new DateTime();
$expiryDate->modify("+2 months");

$response->setExpires($expiryDate);

The Response component automatically shows the date in GMT timezone as expected in an Expires header.

If we set this value to a date in the past the browser will always refresh the requested page:

<?php

$expiryDate = new DateTime();
$expiryDate->modify("-10 minutes");

$response->setExpires($expiryDate);

Browsers rely on the client’s clock to assess if this date has passed or not. The client clock can be modified to make pages expire and this may represent a limitation for this cache mechanism.

Cache-Control

This header provides a safer way to cache the pages served. We simply must specify a time in seconds telling the browser how long it must keep the page in its cache:

<?php

// Starting from now, cache the page for one day
$response->setHeader("Cache-Control", "max-age=86400");

The opposite effect (avoid page caching) is achieved in this way:

<?php

// Never cache the served page
$response->setHeader("Cache-Control", "private, max-age=0, must-revalidate");
E-Tag

An “entity-tag” or “E-tag” is a unique identifier that helps the browser realize if the page has changed or not between two requests. The identifier must be calculated taking into account that this must change if the previously served content has changed:

<?php

// Calculate the E-Tag based on the modification time of the latest news
$mostRecentDate = News::maximum(
    [
        "column" => "created_at"
    ]
);

$eTag = md5($mostRecentDate);

// Send an E-Tag header
$response->setHeader("E-Tag", $eTag);

生成 URL 和 路径(Generating URLs and Paths)

Phalcon\Mvc\Url is the component responsible of generate URLs in a Phalcon application. It’s capable of produce independent URLs based on routes.

Phalcon\Mvc\Url 组件负责在Phalcon应用内生成URL。它依赖路由生成独立的URL。

设置站点基地址(Setting a base URI)

Depending of which directory of your document root your application is installed, it may have a base URI or not.

For example, if your document root is /var/www/htdocs and your application is installed in /var/www/htdocs/invo then your baseUri will be /invo/. If you are using a VirtualHost or your application is installed on the document root, then your baseUri is /. Execute the following code to know the base URI detected by Phalcon:

<?php

use Phalcon\Mvc\Url;

$url = new Url();

echo $url->getBaseUri();

By default, Phalcon automatically may detect your baseUri, but if you want to increase the performance of your application is recommended setting up it manually:

<?php

use Phalcon\Mvc\Url;

$url = new Url();

// Setting a relative base URI
$url->setBaseUri("/invo/");

// Setting a full domain as base URI
$url->setBaseUri("//my.domain.com/");

// Setting a full domain as base URI
$url->setBaseUri("http://my.domain.com/my-app/");

Usually, this component must be registered in the Dependency Injector container, so you can set up it there:

<?php

use Phalcon\Mvc\Url;

$di->set(
    "url",
    function () {
        $url = new Url();

        $url->setBaseUri("/invo/");

        return $url;
    }
);
生成 URI(Generating URIs)

If you are using the Router with its default behavior. Your application is able to match routes based on the following pattern: /:controller/:action/:params. Accordingly it is easy to create routes that satisfy that pattern (or any other pattern defined in the router) passing a string to the method “get”:

<?php echo $url->get("products/save"); ?>

Note that isn’t necessary to prepend the base URI. If you have named routes you can easily change it creating it dynamically. For Example if you have the following route:

<?php

$router->add(
    "/blog/{year}/{month}/{title}",
    [
        "controller" => "posts",
        "action"     => "show",
    ]
)->setName("show-post");

A URL can be generated in the following way:

<?php

// This produces: /blog/2015/01/some-blog-post
$url->get(
    [
        "for"   => "show-post",
        "year"  => "2015",
        "month" => "01",
        "title" => "some-blog-post",
    ]
);
没有伪静态状态下的生成 URL(Producing URLs without mod_rewrite)

You can use this component also to create URLs without mod_rewrite:

<?php

use Phalcon\Mvc\Url;

$url = new Url();

// Pass the URI in $_GET["_url"]
$url->setBaseUri("/invo/index.php?_url=/");

// This produce: /invo/index.php?_url=/products/save
echo $url->get("products/save");

You can also use $_SERVER["REQUEST_URI"]:

<?php

use Phalcon\Mvc\Url;

$url = new Url();

// Pass the URI in $_GET["_url"]
$url->setBaseUri("/invo/index.php?_url=/");

// Pass the URI using $_SERVER["REQUEST_URI"]
$url->setBaseUri("/invo/index.php/");

In this case, it’s necessary to manually handle the required URI in the Router:

<?php

use Phalcon\Mvc\Router;

$router = new Router();

// ... Define routes

$uri = str_replace($_SERVER["SCRIPT_NAME"], "", $_SERVER["REQUEST_URI"]);

$router->handle($uri);

The produced routes would look like:

<?php

// This produce: /invo/index.php/products/save
echo $url->get("products/save");
Volt 中生成 URL(Volt Producing URLs from Volt)

The function “url” is available in volt to generate URLs using this component:

<a href="{{ url("posts/edit/1002") }}">Edit</a>

Generate static routes:

<link rel="stylesheet" href="{{ static_url("css/style.css") }}" type="text/css" />
静态 URI 与 动态 URI(Static vs. Dynamic URIs)

This component allow you to set up a different base URI for static resources in the application:

<?php

use Phalcon\Mvc\Url;

$url = new Url();

// Dynamic URIs are
$url->setBaseUri("/");

// Static resources go through a CDN
$url->setStaticBaseUri("http://static.mywebsite.com/");

Phalcon\Tag will request both dynamical and static URIs using this component.

自定义 URL 生成器(Implementing your own URL Generator)

The Phalcon\Mvc\UrlInterface interface must be implemented to create your own URL generator replacing the one provided by Phalcon.

闪存消息(Flashing Messages)

闪存消息用于通知用户关于他/她产生的动作状态,或者简单地为用户显示一此信息。 这类消息可以使用这个组件来生成。

适配器(Adapters)

这个组件使用了适配器来定义消息传递给Flasher后的行为:

适配器 描述 API
Direct 直接输出传递给flasher的消息 Phalcon\Flash\Direct
Session 将消息临时存放于会话中,以便消息可以在后面的请求中打印出来 Phalcon\Flash\Session
使用(Usage)

通常闪存消息都是来自服务容器的请求. 如果你正在使用 Phalcon\Di\FactoryDefault , 那么 Phalcon\Flash\Direct 将会作为 “flash” 服务自动注册 和 Phalcon\Flash\Session 将会作为 “flashSession” 服务自动注册. You can also manually register it:

<?php

use Phalcon\Flash\Direct as FlashDirect;
use Phalcon\Flash\Session as FlashSession;

// 建立flash服务
$di->set(
    "flash",
    function () {
        return new FlashDirect();
    }
);

// 建立flashSession服务
$di->set(
    "flashSession",
    function () {
        return new FlashSession();
    }
);

这样的话,你便可以在控制器或者视图中通过在必要的片段中注入此服务来使用它:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        $this->flash->success("The post was correctly saved!");
    }
}

目前已支持的有四种内置消息类型:

<?php

$this->flash->error("too bad! the form had errors");

$this->flash->success("yes!, everything went very smoothly");

$this->flash->notice("this a very important information");

$this->flash->warning("best check yo self, you're not looking too good.");

你可以用你自己的类型来添加消息:

<?php

$this->flash->message("debug", "this is debug message, you don't say");
输出信息(Printing Messages)

发送给flash服务的消息将会自动格式成html:

<div class="errorMessage">too bad! the form had errors</div>

<div class="successMessage">yes!, everything went very smoothly</div>

<div class="noticeMessage">this a very important information</div>

<div class="warningMessage">best check yo self, you're not looking too good.</div>

正如你看到的,CSS的类将会自动添加到:code:`<div>`中。这些类允许你定义消息在浏览器上的图形表现。 此CSS类可以被重写,例如,如果你正在使用Twitter的Bootstrap,对应的类可以这样配置:

<?php

use Phalcon\Flash\Direct as FlashDirect;

// 利用自定义的CSS类来注册flash服务
$di->set(
    "flash",
    function () {
        $flash = new FlashDirect(
            [
                "error"   => "alert alert-danger",
                "success" => "alert alert-success",
                "notice"  => "alert alert-info",
                "warning" => "alert alert-warning",
            ]
        );

        return $flash;
    }
);

然后消息会是这样输出:

<div class="alert alert-danger">too bad! the form had errors</div>

<div class="alert alert-success">yes!, everything went very smoothly</div>

<div class="alert alert-info">this a very important information</div>

<div class="alert alert-warning">best check yo self, you're not looking too good.</div>
绝对刷送与会话(Implicit Flush vs. Session)

依赖于发送消息的适配器,它可以立即产生输出,也可以先临时将消息存放于会话中随后再显示。 你何时应该使用哪个?这通常依赖于你在发送消息后重定向的类型。例如, 如果你用了“转发”则不需要将消息存放于会话中,但如果你用的是一个HTTP重定向,那么则需要存放于会话中:

<?php

use Phalcon\Mvc\Controller;

class ContactController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // 存储POST

        // 使用直接闪存
        $this->flash->success("Your information was stored correctly!");

        // 转发到index动作
        return $this->dispatcher->forward(
            [
                "action" => "index"
            ]
        );
    }
}

或者使用一个HTTP重定向:

<?php

use Phalcon\Mvc\Controller;

class ContactController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // 存储POST

        // 使用会话闪存
        $this->flashSession->success("Your information was stored correctly!");

        // 返回一个完整的HTTP重定向
        return $this->response->redirect("contact/index");
    }
}

在这种情况下,你需要手动在交互的视图上打印消息:

<!-- app/views/contact/index.phtml -->

<p><?php $this->flashSession->output() ?></p>

“flashSession”属性是先前在依赖注入容器中设置的闪存。 为了能成功使用flashSession消息者,你需要先启动 session

使用 Session 存储数据(Storing data in Session)

会话组件组件提供了一种面向对象的方式访问session数据。

使用这个组件替代原生session的原因如下:

  • 在相同域名下的不同应用程序之间,你可以非常容易的隔离session数据
  • Intercept where session data is set/get in your application
  • 根据应用程序的需要,可以非常方便的更换session适配器
启动会话(Starting the Session)

Some applications are session-intensive, almost any action that performs requires access to session data. There are others who access session data casually. Thanks to the service container, we can ensure that the session is accessed only when it’s clearly needed:

<?php

use Phalcon\Session\Adapter\Files as Session;

// Start the session the first time when some component request the session service
$di->setShared(
    "session",
    function () {
        $session = new Session();

        $session->start();

        return $session;
    }
);
Session 的存储与读取(Storing/Retrieving data in Session)

控制器,视图或者任何继承于 Phalcon\Di\Injectable 的组件,都可以访问session服务。 如下示例介绍了session的存储与读取操作:

<?php

use Phalcon\Mvc\Controller;

class UserController extends Controller
{
    public function indexAction()
    {
        // 设置一个session变量
        $this->session->set("user-name", "Michael");
    }

    public function welcomeAction()
    {
        // 检查session变量是否已定义
        if ($this->session->has("user-name")) {
            // 获取session变量的值
            $name = $this->session->get("user-name");
        }
    }

}
Sessions 的删除和销毁(Removing/Destroying Sessions)

你也可以删除某个session变量,或者销毁全部session会话:

<?php

use Phalcon\Mvc\Controller;

class UserController extends Controller
{
    public function removeAction()
    {
        // 删除session变量
        $this->session->remove("user-name");
    }

    public function logoutAction()
    {
        // 销毁全部session会话
        $this->session->destroy();
    }
}
隔离不同应用的会话数据(Isolating Session Data between Applications)

Sometimes a user can use the same application twice, on the same server, in the same session. Surely, if we use variables in session, we want that every application have separate session data (even though the same code and same variable names). To solve this, you can add a prefix for every session variable created in a certain application:

<?php

use Phalcon\Session\Adapter\Files as Session;

// Isolating the session data
$di->set(
    "session",
    function () {
        // All variables created will prefixed with "my-app-1"
        $session = new Session(
            [
                "uniqueId" => "my-app-1",
            ]
        );

        $session->start();

        return $session;
    }
);

Adding a unique ID is not necessary.

会话袋(Session Bags)

Phalcon\Session\Bag is a component that helps separating session data into “namespaces”. Working by this way you can easily create groups of session variables into the application. By only setting the variables in the “bag”, it’s automatically stored in session:

<?php

use Phalcon\Session\Bag as SessionBag;

$user = new SessionBag("user");

$user->setDI($di);

$user->name = "Kimbra Johnson";
$user->age  = 22;
组件的持久数据(Persistent Data in Components)

Controller, components and classes that extends Phalcon\Di\Injectable may inject a Phalcon\Session\Bag. This class isolates variables for every class. Thanks to this you can persist data between requests in every class in an independent way.

<?php

use Phalcon\Mvc\Controller;

class UserController extends Controller
{
    public function indexAction()
    {
        // Create a persistent variable "name"
        $this->persistent->name = "Laura";
    }

    public function welcomeAction()
    {
        if (isset($this->persistent->name)) {
            echo "Welcome, ", $this->persistent->name;
        }
    }
}

In a component:

<?php

use Phalcon\Mvc\Controller;

class Security extends Component
{
    public function auth()
    {
        // Create a persistent variable "name"
        $this->persistent->name = "Laura";
    }

    public function getAuthName()
    {
        return $this->persistent->name;
    }
}

The data added to the session ($this->session) are available throughout the application, while persistent ($this->persistent) can only be accessed in the scope of the current class.

自定义适配器(Implementing your own adapters)

The Phalcon\Session\AdapterInterface interface must be implemented in order to create your own session adapters or extend the existing ones.

There are more adapters available for this components in the Phalcon Incubator

过滤与清理(Filtering and Sanitizing)

清理用户输入是软件开发中很重要的一个环节。信任或者忽略对用户输入数据作清理可能会导致 对应用内容(主要是用户数据),甚至你应用所处在的服务器的非法访问。

_images/sql.png

Full image (from xkcd)

Phalcon\Filter 组件提供了一系列通用可用的过滤器和数据清理助手。它提供了围绕于PHP过滤扩展的面向对象包装。

内置过滤器类型(Types of Built-in Filters)

以下是该容器提供的内置过滤器:

名称 描述
string 带标签
email 删掉除字母、数字和 !#$%&*+-/=?^_`{|}~@.[] 外的全部字符
int 删掉除R数字、加号、减号外的全部字符
float 删掉除数字、点号和加号、减号外的全部字符
alphanum 删掉除[a-zA-Z0-9]外的全部字符
striptags 调用 strip_tags 方法
trim 调用 trim 方法
lower 调用 strtolower 方法
upper 调用 strtoupper 方法
清理数据(Sanitizing data)

清理是指从一个值中移除特定字符的过程,此过程对用户和应用不是必须,也不是他们想得到的。 通过清理输入,我们确保了应用的完整性和正确性。

<?php

use Phalcon\Filter;

$filter = new Filter();

// 返回 "someone@example.com"
$filter->sanitize("some(one)@exa\mple.com", "email");

// 返回 "hello"
$filter->sanitize("hello<<", "string");

// 返回 "100019"
$filter->sanitize("!100a019", "int");

// 返回 "100019.01"
$filter->sanitize("!100a019.01a", "float");
在控制器中使用清理(Sanitizing from Controllers)

当接收到GET或POST的数据时(通过请求对象),你可以在控制器中访问一个 Phalcon\Filter 对象。 第一个参数是等待获得变量的名字,第二个参数是将应用在此变量的过滤器。

<?php

use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function indexAction()
    {

    }

    public function saveAction()
    {
        // 从输入中清理price
        $price = $this->request->getPost("price", "double");

        // 从输入中清理email
        $email = $this->request->getPost("customerEmail", "email");
    }
}
过滤动作参数(Filtering Action Parameters)

接下来的示例演示了在一个控制器的动作中如何清理动作的参数:

<?php

use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function indexAction()
    {

    }

    public function showAction($productId)
    {
        $productId = $this->filter->sanitize($productId, "int");
    }
}
过滤数据(Filtering data)

此外, Phalcon\Filter 也提供了可以进行删除或者修改输入数据以满足我们需要的格式的过滤器。

<?php

use Phalcon\Filter;

$filter = new Filter();

// 返回 "Hello"
$filter->sanitize("<h1>Hello</h1>", "striptags");

// 返回 "Hello"
$filter->sanitize("  Hello   ", "trim");
Combining Filters

You can also run multiple filters on a string at the same time by passing an array of filter identifiers as the second parameter:

<?php

use Phalcon\Filter;

$filter = new Filter();

// 返回 "Hello"
$filter->sanitize(
    "   <h1> Hello </h1>   ",
    [
        "striptags",
        "trim",
    ]
);
创建过滤器(Creating your own Filters)

你可以将你自己的过滤器添加到 Phalcon\Filter 。过滤器的方法可以是匿名函数:

<?php

use Phalcon\Filter;

$filter = new Filter();

// 使用匿名函数
$filter->add(
    "md5",
    function ($value) {
        return preg_replace("/[^0-9a-f]/", "", $value);
    }
);

// 利用md5过滤器清理
$filtered = $filter->sanitize($possibleMd5, "md5");

或者,如果你愿意,你可以在类中实现过滤器:

<?php

use Phalcon\Filter;

class IPv4Filter
{
    public function filter($value)
    {
        return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
    }
}

$filter = new Filter();

// 使用对象
$filter->add(
    "ipv4",
    new IPv4Filter()
);

// 利用"ipv4"过滤器清理
$filteredIp = $filter->sanitize("127.0.0.1", "ipv4");
复杂的过滤与清理(Complex Sanitizing and Filtering)

你可以使用PHP本身提供的优秀过滤器扩展。请查看对应的文档: PHP文档上的数据过滤器

自定义过滤器(Implementing your own Filter)

如需创建你自己的过滤器并代替Phalcon提供的过滤器,你需要实现 Phalcon\FilterInterface 接口。

上下文编码(Contextual Escaping)

网站及其它B/S应用极易受到 XSS 攻击,尽管PHP提供了转义功能,在某些情况下依然不够安全。在Phalcon中 Phalcon\Escaper 提供了上下文转义功能,这个模块是由C语言实现的, 这在进行转义时可以有更好的性能。

Phalcon的上下文转义组件基于 OWASP 提供的`XSS (Cross Site Scripting) 预防作弊表`_

另外,这个组件依赖于 mbstring 扩展,以支持几乎所有的字符集。

下面的例子中展示了这个组件是如何工作的:

<?php

use Phalcon\Escaper;

// 带有额外的html标签的恶意的文档标题
$maliciousTitle = "</title><script>alert(1)</script>";

// 恶意的css类名
$className = ";`(";

// 恶意的css字体名
$fontName = "Verdana\"</style>";

// 恶意的Javascript文本
$javascriptText = "';</script>Hello";

// 创建转义实例对象
$e = new Escaper();

?>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>
            <?php echo $e->escapeHtml($maliciousTitle); ?>
        </title>

        <style type="text/css">
            .<?php echo $e->escapeCss($className); ?> {
                font-family: "<?php echo $e->escapeCss($fontName); ?>";
                color: red;
            }
        </style>

    </head>

    <body>

        <div class='<?php echo $e->escapeHtmlAttr($className); ?>'>
            hello
        </div>

        <script>
            var some = '<?php echo $e->escapeJs($javascriptText); ?>';
        </script>

    </body>
</html>

结果如下:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>
            &lt;/title&gt;&lt;script&gt;alert(1)&lt;/script&gt;
        </title>

        <style type="text/css">
            .\3c \2f style\3e {
                font-family: "Verdana\22 \3c \2f style\3e";
                color: red;
            }
        </style>

    </head>

    <body>

        <div class='&#x3c &#x2f style&#x3e '>
            hello
        </div>

        <script>
            var some = '\x27\x3b\x3c\2fscript\x3eHello';
        </script>

    </body>
</html>

Phalcon会根据文本所处的上下文进行转义。 恰当的上下文环境对防范XSS攻击来说是非常重要的。

HTML 编码(Escaping HTML)

最不安全的情形即是在html标签中插入非安全的数据。

<div class="comments">
    <!-- Escape untrusted data here! -->
</div>

我们可以使用 escapeHtml 方法对这些文本进行转义:

<div class="comments">
    <?php echo $e->escapeHtml('></div><h1>myattack</h1>'); ?>
</div>

结果如下:

<div class="comments">
    &gt;&lt;/div&gt;&lt;h1&gt;myattack&lt;/h1&gt;
</div>
HTML 属性编码(Escaping HTML Attributes)

对html属性进行转义和对html内容进行转义略有不同。对html的属性进行转义是通过对所有的非字母和数字转义来实现的。类例的转义都会如此进行的,除了一些复杂的属性外如:href和url:

<table width="Escape untrusted data here!">
    <tr>
        <td>
            Hello
        </td>
    </tr>
</table>

我们这里使用 escapeHtmlAttr 方法对html属性进行转义:

<table width="<?php echo $e->escapeHtmlAttr('"><h1>Hello</table'); ?>">
    <tr>
        <td>
            Hello
        </td>
    </tr>
</table>

结果如下:

<table width="&#x22;&#x3e;&#x3c;h1&#x3e;Hello&#x3c;&#x2f;table">
    <tr>
        <td>
            Hello
        </td>
    </tr>
</table>
URL 编码(Escaping URLs)

一些html的属性如href或url需要使用特定的方法进行转义:

<a href="Escape untrusted data here!">
    Some link
</a>

我们这里使用 escapeUrl 方法进行url的转义:

<a href="<?php echo $e->escapeUrl('"><script>alert(1)</script><a href="#'); ?>">
    Some link
</a>

结果如下:

<a href="%22%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E%3Ca%20href%3D%22%23">
    Some link
</a>
CSS 编码(Escaping CSS)

CSS标识/值也可以进行转义:

<a style="color: Escape untrusted data here">
    Some link
</a>

这里我们使用 escapeCss 方法进行转义:

<a style="color: <?php echo $e->escapeCss('"><script>alert(1)</script><a href="#'); ?>">
    Some link
</a>

结果:

<a style="color: \22 \3e \3c script\3e alert\28 1\29 \3c \2f script\3e \3c a\20 href\3d \22 \23 ">
    Some link
</a>
JavaScript 编码(Escaping JavaScript)

插入JavaScript代码的字符串也需要进行适当的转义:

<script>
    document.title = 'Escape untrusted data here';
</script>

这里我们使用 escapeJs 进行转义:

<script>
    document.title = '<?php echo $e->escapeJs("'; alert(100); var x='"); ?>';
</script>
<script>
    document.title = '\x27; alert(100); var x\x3d\x27';
</script>

验证(Validation)

Phalcon\Validation 对Phalcon来说是一个相对独立的组件,它可以对任意的数据进行验证。 当然也可以用来对非模型内的数据进行验证。

下面的例子展示了一些基本的使用方法:

<?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>";
    }
}

由于此模型是松耦合设计的,故此我们也可以使用自己书写的验证工具:

初始化验证(Initializing Validation)

我们可以直接在 Phalcon\Validation 初始化时添加验证链。我们可以把验证器放在一个单独的文件中以提高代码的重用率及可组织性:

<?php

use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;

class MyValidation extends Validation
{
    public function initialize()
    {
        $this->add(
            "name",
            new PresenceOf(
                [
                    "message" => "The name is required",
                ]
            )
        );

        $this->add(
            "email",
            new PresenceOf(
                [
                    "message" => "The e-mail is required",
                ]
            )
        );

        $this->add(
            "email",
            new Email(
                [
                    "message" => "The e-mail is not valid",
                ]
            )
        );
    }
}

Then initialize and use your own validator:

<?php

$validation = new MyValidation();

$messages = $validation->validate($_POST);

if (count($messages)) {
    foreach ($messages as $message) {
        echo $message, "<br>";
    }
}
验证器(Validators)

Phalcon的验证组件中内置了一些验证器:

下面的例子中展示了如何创建自定义的验证器:

<?php

use Phalcon\Validation;
use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;

class IpValidator extends Validator
{
    /**
     * 执行验证
     *
     * @param Phalcon\Validation $validator
     * @param string $attribute
     * @return boolean
     */
    public function validate(Validation $validator, $attribute)
    {
        $value = $validator->getValue($attribute);

        if (!filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
            $message = $this->getOption("message");

            if (!$message) {
                $message = "The IP is not valid";
            }

            $validator->appendMessage(
                new Message($message, $attribute, "Ip")
            );

            return false;
        }

        return true;
    }
}

最重要的一点即是难证器要返回一个布尔值以标识验证是否成功:

验证信息(Validation Messages)

Phalcon\Validation 内置了一个消息子系统,这提供了一个非常好的验证消息回传机制,以便在验证结束后取得验证信息,比如失败原因等。

每个消息由一个 Phalcon\Validation\Message 类的实例构成。 验证过程产生的消息可以使用:code:`getMessages()`方法取得。 每条消息都有一些扩展的信息组成比如产生错误的属性或消息的类型等:

<?php

$messages = $validation->validate();

if (count($messages)) {
    foreach ($messages as $message) {
        echo "Message: ", $message->getMessage(), "\n";
        echo "Field: ", $message->getField(), "\n";
        echo "Type: ", $message->getType(), "\n";
    }
}

我们也可以传送一个message参数以覆盖验证器中默认的信息:

<?php

use Phalcon\Validation\Validator\Email;

$validation->add(
    "email",
    new Email(
        [
            "message" => "The e-mail is not valid",
        ]
    )
);

默认,:code:`getMessages()`方法会返回在验证过程中所产生的信息。 我们可以使用:code:`filter()`方法来过滤我们感兴趣的消息:

<?php

$messages = $validation->validate();

if (count($messages)) {
    // Filter only the messages generated for the field 'name'
    $filteredMessages = $messages->filter("name");

    foreach ($filteredMessages as $message) {
        echo $message;
    }
}
过滤数据(Filtering of Data)

我们可以在数据被验证之前对其先进行过滤,以确保那些恶意的或不正确的数据不被验证。

<?php

use Phalcon\Validation;

$validation = new Validation();

$validation->add(
    "name",
    new PresenceOf(
        [
            "message" => "The name is required",
        ]
    )
);

$validation->add(
    "email",
    new PresenceOf(
        [
            "message" => "The email is required",
        ]
    )
);

// Filter any extra space
$validation->setFilters("name", "trim");
$validation->setFilters("email", "trim");

这里我们使用 filter 组件进行过滤。 我们还可以使用自定义的或内置的过滤器。

验证事件(Validation Events)

当在类中执行验证时, 我们可以在:code:`beforeValidation()`或:code:`afterValidation()`方法(事件)中执行额外的检查,过滤,清理等工作。 如果:code:`beforeValidation()`方法返回了false 则验证会被中止:

<?php

use Phalcon\Validation;

class LoginValidation extends Validation
{
    public function initialize()
    {
        // ...
    }

    /**
     * 验证执行之前执行
     *
     * @param array $data
     * @param object $entity
     * @param Phalcon\Validation\Message\Group $messages
     * @return bool
     */
    public function beforeValidation($data, $entity, $messages)
    {
        if ($this->request->getHttpHost() !== "admin.mydomain.com") {
            $messages->appendMessage(
                new Message("Only users can log on in the administration domain")
            );

            return false;
        }

        return true;
    }

    /**
     * 验证之后执行
     *
     * @param array $data
     * @param object $entity
     * @param Phalcon\Validation\Message\Group $messages
     */
    public function afterValidation($data, $entity, $messages)
    {
        // ... Add additional messages or perform more validations
    }
}
取消验证(Cancelling Validations)

默认所有的验证器都会被执行,不管验证成功与否。 我们可以通过设置 cancelOnFail 参数为 true 来指定某个验证器验证失败时中止以后的所有验证:

<?php

use Phalcon\Validation;
use Phalcon\Validation\Validator\Regex;
use Phalcon\Validation\Validator\PresenceOf;

$validation = new Validation();

$validation->add(
    "telephone",
    new PresenceOf(
        [
            "message"      => "The telephone is required",
            "cancelOnFail" => true,
        ]
    )
);

$validation->add(
    "telephone",
    new Regex(
        [
            "message" => "The telephone is required",
            "pattern" => "/\+44 [0-9]+/",
        ]
    )
);

$validation->add(
    "telephone",
    new StringLength(
        [
            "messageMinimum" => "The telephone is too short",
            "min"            => 2,
        ]
    )
);

第一个验证器中 cancelOnFail 参数设置为 true 则表示如果此验证器验证失败则验证链中接下的验证不会被执行。

我们可以在自定义的验证器中设置 cancelOnFail 为 true 来停止验证链:

<?php

use Phalcon\Validation;
use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;

class MyValidator extends Validator
{
    /**
     * 执行验证
     *
     * @param Phalcon\Validation $validator
     * @param string $attribute
     * @return boolean
     */
    public function validate(Validation $validator, $attribute)
    {
        // If the attribute value is name we must stop the chain
        if ($attribute === "name") {
            $validator->setOption("cancelOnFail", true);
        }

        // ...
    }
}
Avoid validate empty values

You can pass the option ‘allowEmpty’ to all the built-in validators to avoid the validation to be performed if an empty value is passed:

<?php

use Phalcon\Validation;
use Phalcon\Validation\Validator\Regex;

$validation = new Validation();

$validation->add(
    "telephone",
    new Regex(
        [
            "message"    => "The telephone is required",
            "pattern"    => "/\+44 [0-9]+/",
            "allowEmpty" => true,
        ]
    )
);
Recursive Validation

You can also run Validation instances within another via the afterValidation() method. In this example, validating the CompanyValidation instance will also check the PhoneValidation instance:

<?php

use Phalcon\Validation;

class CompanyValidation extends Validation
{
    /**
     * @var PhoneValidation
     */
    protected $phoneValidation;



    public function initialize()
    {
        $this->phoneValidation = new PhoneValidation();
    }



    public function afterValidation($data, $entity, $messages)
    {
        $phoneValidationMessages = $this->phoneValidation->validate(
            $data["phone"]
        );

        $messages->appendMessages(
            $phoneValidationMessages
        );
    }
}

表单(Forms)

Phalcon中提供了 Phalcon\Forms 组件以方便开发者创建和维护应用中的表单。

下面的例子中展示了基本的使用方法:

<?php

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",
        [
            "H" => "Home",
            "C" => "Cell",
        ]
    )
);

可在表单定义时穿插使用表单元素的字义:

<h1>
    Contacts
</h1>

<form method="post">

    <p>
        <label>
            Name
        </label>

        <?php echo $form->render("name"); ?>
    </p>

    <p>
        <label>
            Telephone
        </label>

        <?php echo $form->render("telephone"); ?>
    </p>

    <p>
        <label>
            Type
        </label>

        <?php echo $form->render("telephoneType"); ?>
    </p>



    <p>
        <input type="submit" value="Save" />
    </p>

</form>

开发者可根据需要渲染HTML组件。 当使用:code:render()`函数时, phalcon内部会使用 :doc:`Phalcon\Tag <../api/Phalcon_Tag> 生成相应的html项, 第二个参数中可以对一些属性进行设置。

<p>
    <label>
        Name
    </label>

    <?php echo $form->render("name", ["maxlength" => 30, "placeholder" => "Type your name"]); ?>
</p>

HTML的属性也可以在创建时指定:

<?php

$form->add(
    new Text(
        "name",
        [
            "maxlength"   => 30,
            "placeholder" => "Type your name",
        ]
    )
);
初始化表单(Initializing forms)

从上面的例子我们可以看到表单项也可以在form对象初始化后进行添加。 当然开发者也可以对原有的Form类进行扩展:

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Select;

class ContactForm extends Form
{
    public function initialize()
    {
        $this->add(
            new Text(
                "name"
            )
        );

        $this->add(
            new Text(
                "telephone"
            )
        );

        $this->add(
            new Select(
                "telephoneType",
                TelephoneTypes::find(),
                [
                    "using" => [
                        "id",
                        "name",
                    ]
                ]
            )
        );
    }
}

由于 Phalcon\Forms\Form 实现了 Phalcon\Di\Injectable 接口, 所以开发者可以根据自己的需要访问应用中的服务。

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Hidden;

class ContactForm extends Form
{
    /**
     * This method returns the default value for field 'csrf'
     */
    public function getCsrf()
    {
        return $this->security->getToken();
    }

    public function initialize()
    {
        // Set the same form as entity
        $this->setEntity($this);

        // Add a text element to capture the 'email'
        $this->add(
            new Text(
                "email"
            )
        );

        // Add a text element to put a hidden CSRF
        $this->add(
            new Hidden(
                "csrf"
            )
        );
    }
}

相关的实体在初始化时添加到表单, 自定义的选项通过构造器传送:

<?php

use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Text;
use Phalcon\Forms\Element\Hidden;

class UsersForm extends Form
{
    /**
     * Forms initializer
     *
     * @param Users $user
     * @param array $options
     */
    public function initialize(Users $user, array $options)
    {
        if ($options["edit"]) {
            $this->add(
                new Hidden(
                    "id"
                )
            );
        } else {
            $this->add(
                new Text(
                    "id"
                )
            );
        }

        $this->add(
            new Text(
                "name"
            )
        );
    }
}

在表单实例中必须要这样使用:

<?php

$form = new UsersForm(
    new Users(),
    [
        "edit" => true,
    ]
);
验证(Validation)

Phalcon表单组件可以和 validation 集成,以提供验证。 开发者要单独为每个html元素提供内置或自定义的验证器。

<?php

use Phalcon\Forms\Element\Text;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\StringLength;

$name = new Text(
    "name"
);

$name->addValidator(
    new PresenceOf(
        [
            "message" => "The name is required",
        ]
    )
);

$name->addValidator(
    new StringLength(
        [
            "min"            => 10,
            "messageMinimum" => "The name is too short",
        ]
    )
);

$form->add($name);

然后, 开发者可以根据用户的输入进行验证:

<?php

if (!$form->isValid($_POST)) {
    $messages = $form->getMessages();

    foreach ($messages as $message) {
        echo $message, "<br>";
    }
}

验证器执行的顺序和注册的顺序一致。

默认情况下,所有的元素产生的消息是放在一起的, 所以开发者可以使用简单的foreach来遍历消息, 开发者可以按照自己的意愿组织输出:

<?php

foreach ($form->getMessages(false) as $attribute => $messages) {
    echo "Messages generated by ", $attribute, ":", "\n";

    foreach ($messages as $message) {
        echo $message, "<br>";
    }
}

或获取指定元素的消息:

<?php

$messages = $form->getMessagesFor("name");

foreach ($messages as $message) {
    echo $message, "<br>";
}
过滤(Filtering)

表单元素可以在进行验证前先进行过滤, 开发者可以为每个元素设置过滤器:

<?php

use Phalcon\Forms\Element\Text;

$name = new Text(
    "name"
);

// Set multiple filters
$name->setFilters(
    [
        "string",
        "trim",
    ]
);

$form->add($name);



$email = new Text(
    "email"
);

// Set one filter
$email->setFilters(
    "email"
);

$form->add($email);
Learn more about filtering in Phalcon by reading the Filter documentation.
表单与实体(Forms + Entities)

我们可以把 model/collection/plain 设置到表单对象中, 这样 phalcon 会自动的设置表单元素的值:

<?php

$robot = Robots::findFirst();

$form = new Form($robot);

$form->add(
    new Text(
        "name"
    )
);

$form->add(
    new Text(
        "year"
    )
);

在表单渲染时如果表单项未设置默认值, phalcon会使用对象实体值作为默认值:

<?php echo $form->render("name"); ?>

开发者可以使用下面的方式验证表单及利用用户的输入来设置值:

<?php

$form->bind($_POST, $robot);

// Check if the form is valid
if ($form->isValid()) {
    // Save the entity
    $robot->save();
}

也可以使用一个简单的类做为对象实体进行参数传递:

<?php

class Preferences
{
    public $timezone = "Europe/Amsterdam";

    public $receiveEmails = "No";
}

使用此类做为对象实体,这样可以使用此类中的值作为表单的默认值:

<?php

$form = new Form(
    new Preferences()
);

$form->add(
    new Select(
        "timezone",
        [
            "America/New_York"  => "New York",
            "Europe/Amsterdam"  => "Amsterdam",
            "America/Sao_Paulo" => "Sao Paulo",
            "Asia/Tokyo"        => "Tokyo",
        ]
    )
);

$form->add(
    new Select(
        "receiveEmails",
        [
            "Yes" => "Yes, please!",
            "No"  => "No, thanks",
        ]
    )
);

实体中也可以使用getters, 这样可以给开发者更多的自由, 当然也会洽使开发稍麻烦一些,不过这是值得的:

<?php

class Preferences
{
    public $timezone;

    public $receiveEmails;



    public function getTimezone()
    {
        return "Europe/Amsterdam";
    }

    public function getReceiveEmails()
    {
        return "No";
    }
}
表单控件(Form Elements)

Phalcon提供了一些内置的html元素类, 所有这些元素类仅位于 Phalcon\Forms\Element 命名空间下:

名称 描述
Phalcon\Forms\Element\Text 产生 INPUT[type=text] 项
Phalcon\Forms\Element\Password 产生 INPUT[type=password] 项
Phalcon\Forms\Element\Select 产生 SELECT tag (combo lists) 项
Phalcon\Forms\Element\Check 产生 INPUT[type=check] 项
Phalcon\Forms\Element\TextArea 产生 TEXTAREA 项
Phalcon\Forms\Element\Hidden 产生 INPUT[type=hidden] 项
Phalcon\Forms\Element\File 产生 INPUT[type=file] 项
Phalcon\Forms\Element\Date 产生 INPUT[type=date] 项
Phalcon\Forms\Element\Numeric 产生 INPUT[type=number] 项
Phalcon\Forms\Element\Submit 产生 INPUT[type=submit] 项
事件回调(Event Callbacks)

当扩展表单时, 我们可以在表单类中实现验证前操作及验证后操作:

<?php

use Phalcon\Forms\Form;

class ContactForm extends Form
{
    public function beforeValidation()
    {

    }
}
渲染表单(Rendering Forms)

开发者对表单的渲染操作有完全的控制, 下面的的例子展示了如何使用标准方法渲染html元素:

<?php

<form method="post">
    <?php

        // Traverse the form
        foreach ($form as $element) {
            // Get any generated messages for the current element
            $messages = $form->getMessagesFor(
                $element->getName()
            );

            if (count($messages)) {
                // Print each element
                echo '<div class="messages">';

                foreach ($messages as $message) {
                    echo $message;
                }

                echo "</div>";
            }

            echo "<p>";

            echo '<label for="', $element->getName(), '">', $element->getLabel(), "</label>";

            echo $element;

            echo "</p>";
        }

    ?>

    <input type="submit" value="Send" />
</form>

或是在登录表单中重用表单类:

<?php

use Phalcon\Forms\Form;

class ContactForm extends Form
{
    public function initialize()
    {
        // ...
    }

    public function renderDecorated($name)
    {
        $element  = $this->get($name);

        // Get any generated messages for the current element
        $messages = $this->getMessagesFor(
            $element->getName()
        );

        if (count($messages)) {
            // Print each element
            echo '<div class="messages">';

            foreach ($messages as $message) {
                echo $this->flash->error($message);
            }

            echo "</div>";
        }

        echo "<p>";

        echo '<label for="', $element->getName(), '">', $element->getLabel(), "</label>";

        echo $element;

        echo "</p>";
    }
}

视图中:

<?php

echo $element->renderDecorated("name");

echo $element->renderDecorated("telephone");
创建表单控件(Creating Form Elements)

除了可以使用phalcon提供的html元素以外, 开发者还可以使用自定义的html元素:

<?php

use Phalcon\Forms\Element;

class MyElement extends Element
{
    public function render($attributes = null)
    {
        $html = // ... Produce some HTML

        return $html;
    }
}
表单管理(Forms Manager)

此组件为开发者提供了一个表单管理器, 可以用来注册表单,此组件可以使用服务容器来访问:

<?php

use Phalcon\Forms\Manager as FormsManager;

$di["forms"] = function () {
    return new FormsManager();
};

表单被添加到表单管理器, 然后设置了唯一的名字:

<?php

$this->forms->set(
    "login",
    new LoginForm()
);

使用唯一名, 我们可以在应用的任何地方访问到表单:

<?php

$loginForm = $this->forms->get("login");

echo $loginForm->render();
外部资源(External Resources)
  • Vökuró 是一个使用表单构建器来创建和维护表单的示例 [Github]

读取配置(Reading Configurations)

Phalcon\Config 是一个用于将各种格式的配置文件读取到PHP对象的组件(使用适配器)。

原生数组(Native Arrays)

下面的例子展示如何将本地数组导入 Phalcon\Config 对象。此选项提供了最好的性能,因为在这个请求中没有读取文件。

<?php

use Phalcon\Config;

$settings = [
    "database" => [
        "adapter"  => "Mysql",
        "host"     => "localhost",
        "username" => "scott",
        "password" => "cheetah",
        "dbname"   => "test_db"
    ],
     "app" => [
        "controllersDir" => "../app/controllers/",
        "modelsDir"      => "../app/models/",
        "viewsDir"       => "../app/views/"
    ],
    "mysetting" => "the-value"
];

$config = new Config($settings);

echo $config->app->controllersDir, "\n";
echo $config->database->username, "\n";
echo $config->mysetting, "\n";

如果你想更好的组织你的项目,你可以在另一个文件保存数组,然后读入它。

<?php

use Phalcon\Config;

require "config/config.php";

$config = new Config($settings);
文件适配器(File Adapters)

可用的适配器有:

Class 解释
Phalcon\Config\Adapter\Ini 使用INI文件来存储设置。内部适配器使用PHP函数 parse_ini_file。
Phalcon\Config\Adapter\Json Uses JSON files to store settings.
Phalcon\Config\Adapter\Php Uses PHP multidimensional arrays to store settings. This adapter offers the best performance.
Phalcon\Config\Adapter\Yaml Uses YAML files to store settings.
读取 INI 文件(Reading INI Files)

INI文件是存储设置的常用方法。 Phalcon\Config 采用优化的PHP函数parse_ini_file读取这些文件。为方便访问,文件部分解析成子设置。

[database]
adapter  = Mysql
host     = localhost
username = scott
password = cheetah
dbname   = test_db

[phalcon]
controllersDir = "../app/controllers/"
modelsDir      = "../app/models/"
viewsDir       = "../app/views/"

[models]
metadata.adapter  = "Memory"

你可以阅读如下所示的文件:

<?php

use Phalcon\Config\Adapter\Ini as ConfigIni;

$config = new ConfigIni("path/config.ini");

echo $config->phalcon->controllersDir, "\n";
echo $config->database->username, "\n";
echo $config->models->metadata->adapter, "\n";
合并配置(Merging Configurations)

Phalcon\Config 允许合并配置对象到另一个:

<?php

use Phalcon\Config;

$config = new Config(
    [
        "database" => [
            "host"   => "localhost",
            "dbname" => "test_db",
        ],
        "debug" => 1,
    ]
);

$config2 = new Config(
    [
        "database" => [
            "dbname"   => "production_db",
            "username" => "scott",
            "password" => "secret",
        ],
        "logging" => 1,
    ]
);

$config->merge($config2);

print_r($config);

上面的代码会产生以下内容:

Phalcon\Config Object
(
    [database] => Phalcon\Config Object
        (
            [host] => localhost
            [dbname]   => production_db
            [username] => scott
            [password] => secret
        )
    [debug] => 1
    [logging] => 1
)

有更多的适配器可用于这个组件: Phalcon Incubator

Injecting Configuration Dependency

You can inject configuration dependency to controller allowing us to use Phalcon\Config inside Phalcon\Mvc\Controller. To be able to do that, add following code inside your dependency injector script.

<?php

use Phalcon\Di\FactoryDefault;
use Phalcon\Config;

// Create a DI
$di = new FactoryDefault();

$di->set(
    "config",
    function () {
        $configData = require "config/config.php";

        return new Config($configData);
    }
);

Now in your controller you can access your configuration by using dependency injection feature using name config like following code:

<?php

use Phalcon\Mvc\Controller;

class MyController extends Controller
{
    private function getDatabaseName()
    {
        return $this->config->database->dbname;
    }
}

使用缓存提高性能(Improving Performance with Cache)

Phalcon提供的 Phalcon\Cache 类可以更快地接入获取使用频繁或者已经被处理的数据。 Phalcon\Cache 是用C来编写的,因此有着更高的性能并且能够减少从后端获取昂价资源所带来的负载。 这个类使用了由前端和后端组件组成的内部结构。前端组件如输入源或者接口,后端组件则为这个类提供了存储的选项。

什么情况下使用缓存?(When to implement cache?)

尽管这个组件运行非常快速,但如果不加考虑就使用它会适得其反,特别在不需要或者不适宜使用缓存时。 我们建议你在使用缓存前核对一下场景:

  • 你正在进行复杂的运算,并且每次都返回相同的结果(或者变动很少)
  • 你正在使用大量的插件生成大部分时间几乎都是相同的页面输出
  • 你正在频繁地接入数据库并且这些数据变动甚少
温馨提示 即使使用了这些缓存,你仍然应该定期检测缓存的命中率。 通过后台提供的相关工具,这一点很容易做得到,特别是使用Memcache或者APC时。
缓存行为(Caching Behavior)

缓存流程可以分为两部分:

  • 前端: 此部分负责检测是否key已失效并且在保存数据和抓取数据后提供额外的转换操作。
  • 后端: 此部分负责通讯,并根据前端进行数据的读/写。
缓存输出片段(Caching Output Fragments)

输出片段是指一小块缓存和返回都一样的HTML或者文本内容。输出的内容应该是能自动 被 ob_* 函数捕获或者直接是PHP输出,这样才能缓存起来。以下实例演示了这样的使用。 它接收PHP生成的页面输出并保存在一个文件里面。缓存文件的内容每隔172800秒(2天)刷新一次。

使用这个缓存机制,无论何时调用这块代码,我们都可以通过避免重复执行辅助插件 Phalcon\Tag::linkTo() 从而获得更高的性能。

<?php

use Phalcon\Tag;
use Phalcon\Cache\Backend\File as BackFile;
use Phalcon\Cache\Frontend\Output as FrontOutput;

// Create an Output frontend. Cache the files for 2 days
$frontCache = new FrontOutput(
    [
        "lifetime" => 172800,
    ]
);

// Create the component that will cache from the "Output" to a "File" backend
// Set the cache file directory - it's important to keep the "/" at the end of
// the value for the folder
$cache = new BackFile(
    $frontCache,
    [
        "cacheDir" => "../app/cache/",
    ]
);

// Get/Set the cache file to ../app/cache/my-cache.html
$content = $cache->start("my-cache.html");

// If $content is null then the content will be generated for the cache
if ($content === null) {
    // Print date and time
    echo date("r");

    // Generate a link to the sign-up action
    echo Tag::linkTo(
        [
            "user/signup",
            "Sign Up",
            "class" => "signup-button",
        ]
    );

    // Store the output into the cache file
    $cache->save();
} else {
    // Echo the cached output
    echo $content;
}

温馨提示 在上面的实例中,我们的代码维持不变,即输出给用户的内容和之前展示的内容是一样的。我们的缓存组件 以透明的方式捕获了页面输出并保存在缓存文件(当缓存生成时)或者在早期的一次调用时将它发送回用户预编译,故而可以避免高昂的操作。

缓存任意数据(Caching Arbitrary Data)

仅仅是缓存数据,对于你的应用来说也是同等重要的。缓存通过重用常用的(非更新的)数据可以减少数据库的加载, 从而加速你的应用。

文件后端存储器例子(File Backend Example)

其中一个缓存适配器是文件’File’。文件适配器的配置中只需要一个key:指明缓存文件存放的目录位置。 这个配置通过cacheDir选项控制,必须,且要以反斜杠结尾。

<?php

use Phalcon\Cache\Backend\File as BackFile;
use Phalcon\Cache\Frontend\Data as FrontData;

// Cache the files for 2 days using a Data frontend
$frontCache = new FrontData(
    [
        "lifetime" => 172800,
    ]
);

// Create the component that will cache "Data" to a "File" backend
// Set the cache file directory - important to keep the "/" at the end of
// the value for the folder
$cache = new BackFile(
    $frontCache,
    [
        "cacheDir" => "../app/cache/",
    ]
);

$cacheKey = "robots_order_id.cache";

// Try to get cached records
$robots = $cache->get($cacheKey);

if ($robots === null) {
    // $robots is null because of cache expiration or data does not exist
    // Make the database call and populate the variable
    $robots = Robots::find(
        [
            "order" => "id",
        ]
    );

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}
Memcached 后端存储器例子(Memcached Backend Example)

当我们改用Memcached作为后端存储器时,上面的实例改动很轻微(特别就配置而言)。

<?php

use Phalcon\Cache\Frontend\Data as FrontData;
use Phalcon\Cache\Backend\Libmemcached as BackMemCached;

// Cache data for one hour
$frontCache = new FrontData(
    [
        "lifetime" => 3600,
    ]
);

// Create the component that will cache "Data" to a "Memcached" backend
// Memcached connection settings
$cache = new BackMemCached(
    $frontCache,
    [
        "servers" => [
            [
                "host"   => "127.0.0.1",
                "port"   => "11211",
                "weight" => "1",
            ]
        ]
    ]
);

$cacheKey = "robots_order_id.cache";

// Try to get cached records
$robots = $cache->get($cacheKey);

if ($robots === null) {
    // $robots is null because of cache expiration or data does not exist
    // Make the database call and populate the variable
    $robots = Robots::find(
        [
            "order" => "id",
        ]
    );

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
   echo $robot->name, "\n";
}
查询缓存(Querying the cache)

添加到缓存的元素根据唯一的key进行识别区分。这使用文件缓存作为后端时,key就是实际的文件名。 为了从缓存中获得数据,我们仅仅需要通过唯一的key调用即可。如果key不存在,get方法将会返回null。

<?php

// Retrieve products by key "myProducts"
$products = $cache->get("myProducts");

如果你想知道在缓存中存放了哪些key,你可以调用queryKeys方法:

<?php

// Query all keys used in the cache
$keys = $cache->queryKeys();

foreach ($keys as $key) {
    $data = $cache->get($key);

    echo "Key=", $key, " Data=", $data;
}

// Query keys in the cache that begins with "my-prefix"
$keys = $cache->queryKeys("my-prefix");
删除缓存数据(Deleting data from the cache)

有些时机你需要强制废除一个缓存的实体(如对被缓存的数据进行了更新)。 而仅仅需要做的只是知道对应缓存的数据存放于哪个key即可。

<?php

// Delete an item with a specific key
$cache->delete("someKey");

$keys = $cache->queryKeys();

// Delete all items from the cache
foreach ($keys as $key) {
    $cache->delete($key);
}
检查缓存是否存在(Checking cache existence)

也有可能需要根据一个给定的key来判断缓存是否存在:

<?php

if ($cache->exists("someKey")) {
    echo $cache->get("someKey");
} else {
    echo "Cache does not exists!";
}
有效期(Lifetime)

“有效期”是指缓存可以多久时间(在以秒为单位)内有效。默认情况下,全部被创建的缓存都使用前端构建中设定的有效期。 你可以在创建时指定一个有效期或者在从缓存中获取数据时:

Setting the lifetime when retrieving:

<?php

$cacheKey = "my.cache";

// Setting the cache when getting a result
$robots = $cache->get($cacheKey, 3600);

if ($robots === null) {
    $robots = "some robots";

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

在保存时设置有效期:

<?php

$cacheKey = "my.cache";

$robots = $cache->get($cacheKey);

if ($robots === null) {
    $robots = "some robots";

    // Setting the cache when saving data
    $cache->save($cacheKey, $robots, 3600);
}
多级缓存(Multi-Level Cache)

缓存组件的特点,就是允许开发人员使用多级缓存。这个新特性非常有用, 因为你可以在多个缓存媒介结合不同的有效期中保存相同的数据,并在有效期内从首个最快的缓存适配器开始读取,直至到最慢的适配器。

<?php

use Phalcon\Cache\Multiple;
use Phalcon\Cache\Backend\Apc as ApcCache;
use Phalcon\Cache\Backend\File as FileCache;
use Phalcon\Cache\Frontend\Data as DataFrontend;
use Phalcon\Cache\Backend\Memcache as MemcacheCache;

$ultraFastFrontend = new DataFrontend(
    [
        "lifetime" => 3600,
    ]
);

$fastFrontend = new DataFrontend(
    [
        "lifetime" => 86400,
    ]
);

$slowFrontend = new DataFrontend(
    [
        "lifetime" => 604800,
    ]
);

// Backends are registered from the fastest to the slower
$cache = new Multiple(
    [
        new ApcCache(
            $ultraFastFrontend,
            [
                "prefix" => "cache",
            ]
        ),
        new MemcacheCache(
            $fastFrontend,
            [
                "prefix" => "cache",
                "host"   => "localhost",
                "port"   => "11211",
            ]
        ),
        new FileCache(
            $slowFrontend,
            [
                "prefix"   => "cache",
                "cacheDir" => "../app/cache/",
            ]
        ),
    ]
);

// Save, saves in every backend
$cache->save("my-key", $data);
前端适配器(Frontend Adapters)

作为缓存的接口或者输入源的前端适配器有:

适配器 描述
Phalcon\Cache\Frontend\Output 从标准PHP输出读取输入数据
Phalcon\Cache\Frontend\Data 可用于缓存任何类型的PHP数据(大数组,对象,文本等)。在存入后端前数据将会被序列化。
Phalcon\Cache\Frontend\Base64 可用于缓存二进制数据。在存入后端前数据会以base64_encode编码进行序列化。
Phalcon\Cache\Frontend\Json 在存入后端前数据使用JSON编码。从缓存获取后进行JSON解码。此前端适配器可用于跨语言和跨框架共享数据。
Phalcon\Cache\Frontend\Igbinary 用于缓存任何类型的PHP数据(大数组,对象,文本等)。在存入后端前数据会使用IgBinary进行序列化。
Phalcon\Cache\Frontend\None 用于缓存任何类型的PHP数据而不作任何序列化操作。
自定义前端适配器(Implementing your own Frontend adapters)

为了创建你自己的前端适配器或者扩展已有的适配器,你必须 实现 Phalcon\Cache\FrontendInterface 接口。

后端适配器(Backend Adapters)

用于存放缓存数据的后端适配器有:

适配器 描述 信息 需要的扩展
Phalcon\Cache\Backend\File 在本地绝对路径的文件上存放数据    
Phalcon\Cache\Backend\Memcache 在memcached服务器存放数据 Memcached memcache
Phalcon\Cache\Backend\Apc 在opcode缓存 (APC)中存放数据 APC APC extension
Phalcon\Cache\Backend\Mongo 在Mongo数据库中存放数据 MongoDb Mongo
Phalcon\Cache\Backend\Xcache 在XCache中存放数据 XCache xcache extension
Phalcon\Cache\Backend\Redis Stores data in Redis Redis redis extension
自定义后端适配器(Implementing your own Backend adapters)

为了创建你自己的后端适配器或者扩展已有的后端适配器,你必须 实现 Phalcon\Cache\BackendInterface 接口。

文件后端存储器选项(File Backend Options)

此后端存储器把缓存内容存放到本地服务器的文件。对应的选项有:

选项 描述
prefix 自动追加到缓存key前面的前缀
cacheDir 放置缓存文件且可写入的目录
Memcached 后端存储器选项(Memcached Backend Options)

此后端存储器将缓存的内容存放在memcached服务器。对应的选项有:

选项 描述
prefix 自动追加到缓存key前面的前缀
host memcached 域名
port memcached 端口
persistent 创建一个长连接的memcached连接?
APC 后端存储器选项(APC Backend Options)

此后端存储器将缓存内容存放到opcode缓存(APC)。对应的选项有:

选项 描述
prefix 自动追加到缓存key前面的前缀
Mongo 后端存储器选项(Mongo Backend Options)

此后端存储器将缓存内容存放到MongoDB服务器。对应的选项有:

选项 描述
prefix 自动追加到缓存key前面的前缀
server MongoDB的连接串
db Mongo数据库名
collection Mongo数据库连接
XCache 后端存储器选项(XCache Backend Options)

此后端存储器将缓存内容存放到XCache (XCache)。对应的选项有:

选项 描述
prefix 自动追加到缓存key前面的前缀
Redis Backend Options

This backend will store cached content on a Redis server (Redis). The available options for this backend are:

Option Description
prefix A prefix that is automatically prepended to the cache keys
host Redis host
port Redis port
auth Password to authenticate to a password-protected Redis server
persistent Create a persistent connection to Redis
index The index of the Redis database to use

Phalcon Incubator 上还有更多针对这个组件可用的适配器

安全(Security)

该组件可以帮助开发人员在共同安全方面的一些工作,比如密码散列和跨站点请求伪造(CSRF)保护。

密码散列(Password Hashing)

将密码以纯文本方式保存是一个糟糕的安全实践。任何可以访问数据库的人可立即访问所有用户账户,因此能够从事未经授权的活动。为解决这个问题,许多应用程序使用熟悉的 单向散列方法比如”md5“和”sha1“。然而,硬件每天都在发展,变得更快,这些算法在蛮力攻击面前变得脆弱不堪。这些攻击也被称为“彩虹表(rainbow tables )。

为了解决这个问题我们可以使用哈希算法 bcrypt。为什么 bcrypt? 由于其”Eksblowfish“键设置算法,我们可以使密码加密如同我们想要的”慢”。慢的算法使计算 Hash背后的真实密码的过程非常困难甚至不可能。这可以在一个很长一段时间内免遭可能的彩虹表攻击。

这个组件使您能够以一个简单的方法使用该算法:

<?php

use Phalcon\Mvc\Controller;

class UsersController extends Controller
{
    public function registerAction()
    {
        $user = new Users();

        $login    = $this->request->getPost("login");
        $password = $this->request->getPost("password");

        $user->login = $login;

        // Store the password hashed
        $user->password = $this->security->hash($password);

        $user->save();
    }
}

我们保存一个用默认因子散列的密码。更高的因子可以使密码更加可靠。我们可以用如下的方法检查密码是否正确:

<?php

use Phalcon\Mvc\Controller;

class SessionController extends Controller
{
    public function loginAction()
    {
        $login    = $this->request->getPost("login");
        $password = $this->request->getPost("password");

        $user = Users::findFirstByLogin($login);
        if ($user) {
            if ($this->security->checkHash($password, $user->password)) {
                // The password is valid
            }
        } else {
            // To protect against timing attacks. Regardless of whether a user exists or not, the script will take roughly the same amount as it will always be computing a hash.
            $this->security->hash(rand());
        }

        // The validation has failed
    }
}

Salt使用PHP的 openssl_random_pseudo_bytes 函数的伪随机字节生成的,所以需要加载扩展 openssl

防止跨站点请求伪造攻击(Cross-Site Request Forgery (CSRF) protection)

这是另一个常见的web站点和应用程序攻击。如用户注册或添加注释的这类表单就很容易受到这种攻击。

可以想到的方式防止表单值发送自外部应用程序。为了解决这个问题,我们为每个表单生成一个一次性随机令牌(random nonce),在会话中添加令牌,然后一旦表单数据提交到 程序之后,将提交的数据中的的令牌和存储在会中的令牌进行比较,来验证是否合法。

<?php echo Tag::form('session/login') ?>

    <!-- Login and password inputs ... -->

    <input type="hidden" name="<?php echo $this->security->getTokenKey() ?>"
        value="<?php echo $this->security->getToken() ?>"/>

</form>

在控制器的动作中可以检查CSRF令牌是否有效:

<?php

use Phalcon\Mvc\Controller;

class SessionController extends Controller
{
    public function loginAction()
    {
        if ($this->request->isPost()) {
            if ($this->security->checkToken()) {
                // The token is OK
            }
        }
    }
}

记得添加一个会话适配器到依赖注入器中,否则令牌检查是行不通的:

<?php

$di->setShared(
    "session",
    function () {
        $session = new \Phalcon\Session\Adapter\Files();

        $session->start();

        return $session;
    }
);

同时也建议为表单添加一个 captcha ,以完全避免这种攻击的风险。

设置组件(Setting up the component)

该组件自动在服务容器中注册为“security”,你亦可以重新注册它并为它设置参数:

<?php

use Phalcon\Security;

$di->set(
    "security",
    function () {
        $security = new Security();

        // Set the password hashing factor to 12 rounds
        $security->setWorkFactor(12);

        return $security;
    },
    true
);
Random

The Phalcon\Security\Random class makes it really easy to generate lots of types of random data.

<?php

use Phalcon\Security\Random;

$random = new Random();

// ...
$bytes      = $random->bytes();

// Generate a random hex string of length $len.
$hex        = $random->hex($len);

// Generate a random base64 string of length $len.
$base64     = $random->base64($len);

// Generate a random URL-safe base64 string of length $len.
$base64Safe = $random->base64Safe($len);

// Generate a UUID (version 4). See https://en.wikipedia.org/wiki/Universally_unique_identifier
$uuid       = $random->uuid();

// Generate a random integer between 0 and $n.
$number     = $random->number($n);
外部资源(External Resources)
  • Vökuró, 是一个使用的安全组件避免CSRF和密码散列的示例应用程序 [Github]

Encryption/Decryption

Phalcon通过 Phalcon\Crypt 组件提供了加密和解密工具。这个类提供了对PHP openssl 的封装。

默认情况下这个组件使用AES-256-CFB。

You must use a key length corresponding to the current algorithm. For the algorithm used by default it is 32 bytes.
基本使用

这个组件极易使用:

<?php

use Phalcon\Crypt;

// Create an instance
$crypt = new Crypt();

$key  = "This is a secret key (32 bytes).";
$text = "This is the text that you want to encrypt.";

$encrypted = $crypt->encrypt($text, $key);

echo $crypt->decrypt($encrypted, $key);

也可以使用同一实例加密多次:

<?php

use Phalcon\Crypt;

// 创建实例
$crypt = new Crypt();

$texts = [
    "my-key"    => "This is a secret text",
    "other-key" => "This is a very secret",
];

foreach ($texts as $key => $text) {
    // 加密
    $encrypted = $crypt->encrypt($text, $key);

    // 解密
    echo $crypt->decrypt($encrypted, $key);
}
加密选项(Encryption Options)

下面的选项可以改变加密的行为:

名称 描述
Cipher cipher是libmcrypt提供支持的一种加密算法。 查看这里 here

例子:

<?php

use Phalcon\Crypt;

// 创建实例
$crypt = new Crypt();

// 使用 blowfish
$crypt->setCipher("bf-cbc");

$key  = "le password";
$text = "This is a secret text";

echo $crypt->encrypt($text, $key);
提供 Base64(Base64 Support)

为了方便传输或显示我们可以对加密后的数据进行 base64 转码:

<?php

use Phalcon\Crypt;

// 创建实例
$crypt = new Crypt();

$key  = "le password";
$text = "This is a secret text";

$encrypt = $crypt->encryptBase64($text, $key);

echo $crypt->decryptBase64($encrypt, $key);
配置加密服务(Setting up an Encryption service)

你也可以把加密组件放入服务容器中这样我们可以在应用中的任何一个地方访问这个组件:

<?php

use Phalcon\Crypt;

$di->set(
    'crypt',
    function () {
        $crypt = new Crypt();

        // 设置全局加密密钥
        $crypt->setKey(
            "%31.1e$i86e$f!8jz"
        );

        return $crypt;
    },
    true
);

然后,例如,我们可以在控制器中使用它了:

<?php

use Phalcon\Mvc\Controller;

class SecretsController extends Controller
{
    public function saveAction()
    {
        $secret = new Secrets();

        $text = $this->request->getPost("text");

        $secret->content = $this->crypt->encrypt($text);

        if ($secret->save()) {
            $this->flash->success(
                "Secret was successfully created!"
            );
        }
    }
}

访问控制列表 ACL(Access Control Lists ACL)

Phalcon在权限方面通过 Phalcon\Acl 提供了一个轻量级的 ACL(访问控制列表). Access Control Lists (ACL) 允许系统对用户的访问权限进行控制,比如允许访问某些资源而不允许访问其它资源等。 这里我们建议开发者了解一些关于ACL的技术。

ACL有两部分组成即角色和资源。 资源即是ACL定义的权限所依附的对象。 角色即是ACL所字义的请求者的身份,ACL决定了角色对资源的访问权限,允许访问或拒绝访问。

创建 ACL(Creating an ACL)

这个组件起先是设计工作在内存中的, 这样做提供了更高的访问速度。 Phalcon\Acl 构造器的第一个参数用于设置取得ACL的方式。 下面是使用内存适配器的例子:

<?php

use Phalcon\Acl\Adapter\Memory as AclList;

$acl = new AclList();

默认情况下 Phalcon\Acl 允许我们访问未定义的资源中的action,为了提高安全性, 我们设置默认访问级别为‘拒绝’。

<?php

use Phalcon\Acl;

// 设置默认访问级别为拒绝
$acl->setDefaultAction(
    Acl::DENY
);
添加角色(Adding Roles to the ACL)

角色即是权限的集合体,其中定义了我们对资源的访问权限。 例如, 我们会把一个组织内的不同的人定义为不同的角色。 The Phalcon\Acl\Role 类使用一种更有组织的方式来定义角色。 这里我们创建一些角色:

<?php

use Phalcon\Acl\Role;

// 创建角色
// The first parameter is the name, the second parameter is an optional description.
$roleAdmins = new Role("Administrators", "Super-User role");
$roleGuests = new Role("Guests");

// 添加 "Guests" 角色到ACL
$acl->addRole($roleGuests);

// 添加"Designers"到ACL, 仅使用此字符串。
$acl->addRole("Designers");

上面我们看到,我们可以直接使用字符串来定义角色。

添加资源(Adding Resources)

资源即是访问控制要控制的对象之一。 正常情况下在mvc中资源一般是控制器。 Phalcon中我们使用 Phalcon\Acl\Resource 来定义资源。 非常重要的一点即是我们把相关的action或操作添加到资源中这样ACL才知道控制什么资源。

<?php

use Phalcon\Acl\Resource;

// 定义 "Customers" 资源
$customersResource = new Resource("Customers");

// 为 "customers"资源添加一组操作

$acl->addResource(
    $customersResource,
    "search"
);

$acl->addResource(
    $customersResource,
    [
        "create",
        "update",
    ]
);
定义访问控制(Defining Access Controls)

至此我们定义了角色及资源, 现在是定义ACL的时候了,即是定义角色对资源的访问。 这个部分是极其重要的,特别是在我们设定了默认的访问级别后。

<?php

// 设置角色对资源的访问级别
$acl->allow("Guests", "Customers", "search");

$acl->allow("Guests", "Customers", "create");

$acl->deny("Guests", "Customers", "update");

allow()方法指定了允许角色对资源的访问, deny()方法则反之。

查询 ACL(Querying an ACL)

一旦访问控制表定义之后, 我们就可以通过它来检查角色是否有访问权限了。

<?php

// 查询角色是否有访问权限

// Returns 0
$acl->isAllowed("Guests", "Customers", "edit");

// Returns 1
$acl->isAllowed("Guests", "Customers", "search");

// Returns 1
$acl->isAllowed("Guests", "Customers", "create");
Function based access

Also you can add as 4th parameter your custom function which must return boolean value. It will be called when you use isAllowed() method. You can pass parameters as associative array to isAllowed() method as 4th argument where key is parameter name in our defined function.

<?php
// Set access level for role into resources with custom function
$acl->allow(
    "Guests",
    "Customers",
    "search",
    function ($a) {
        return $a % 2 === 0;
    }
);

// Check whether role has access to the operation with custom function

// Returns true
$acl->isAllowed(
    "Guests",
    "Customers",
    "search",
    [
        "a" => 4,
    ]
);

// Returns false
$acl->isAllowed(
    "Guests",
    "Customers",
    "search",
    [
        "a" => 3,
    ]
);

Also if you don’t provide any parameters in isAllowed() method then default behaviour will be Acl::ALLOW. You can change it by using method setNoArgumentsDefaultAction().

use Phalcon\Acl;

<?php
// Set access level for role into resources with custom function
$acl->allow(
    "Guests",
    "Customers",
    "search",
    function ($a) {
        return $a % 2 === 0;
    }
);

// Check whether role has access to the operation with custom function

// Returns true
$acl->isAllowed(
    "Guests",
    "Customers",
    "search"
);

// Change no arguments default action
$acl->setNoArgumentsDefaultAction(
    Acl::DENY
);

// Returns false
$acl->isAllowed(
    "Guests",
    "Customers",
    "search"
);
Objects as role name and resource name

You can pass objects as roleName and resourceName. Your classes must implement Phalcon\Acl\RoleAware for roleName and Phalcon\Acl\ResourceAware for resourceName.

Our UserRole class

<?php

use Phalcon\Acl\RoleAware;

// Create our class which will be used as roleName
class UserRole implements RoleAware
{
    protected $id;

    protected $roleName;

    public function __construct($id, $roleName)
    {
        $this->id       = $id;
        $this->roleName = $roleName;
    }

    public function getId()
    {
        return $this->id;
    }

    // Implemented function from RoleAware Interface
    public function getRoleName()
    {
        return $this->roleName;
    }
}

And our ModelResource class

<?php

use Phalcon\Acl\ResourceAware;

// Create our class which will be used as resourceName
class ModelResource implements ResourceAware
{
    protected $id;

    protected $resourceName;

    protected $userId;

    public function __construct($id, $resourceName, $userId)
    {
        $this->id           = $id;
        $this->resourceName = $resourceName;
        $this->userId       = $userId;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getUserId()
    {
        return $this->userId;
    }

    // Implemented function from ResourceAware Interface
    public function getResourceName()
    {
        return $this->resourceName;
    }
}

Then you can use them in isAllowed() method.

<?php

use UserRole;
use ModelResource;

// Set access level for role into resources
$acl->allow("Guests", "Customers", "search");
$acl->allow("Guests", "Customers", "create");
$acl->deny("Guests", "Customers", "update");

// Create our objects providing roleName and resourceName

$customer = new ModelResource(
    1,
    "Customers",
    2
);

$designer = new UserRole(
    1,
    "Designers"
);

$guest = new UserRole(
    2,
    "Guests"
);

$anotherGuest = new UserRole(
    3,
    "Guests"
);

// Check whether our user objects have access to the operation on model object

// Returns false
$acl->isAllowed(
    $designer,
    $customer,
    "search"
);

// Returns true
$acl->isAllowed(
    $guest,
    $customer,
    "search"
);

// Returns true
$acl->isAllowed(
    $anotherGuest,
    $customer,
    "search"
);

Also you can access those objects in your custom function in allow() or deny(). They are automatically bind to parameters by type in function.

<?php

use UserRole;
use ModelResource;

// Set access level for role into resources with custom function
$acl->allow(
    "Guests",
    "Customers",
    "search",
    function (UserRole $user, ModelResource $model) { // User and Model classes are necessary
        return $user->getId == $model->getUserId();
    }
);

$acl->allow(
    "Guests",
    "Customers",
    "create"
);

$acl->deny(
    "Guests",
    "Customers",
    "update"
);

// Create our objects providing roleName and resourceName

$customer = new ModelResource(
    1,
    "Customers",
    2
);

$designer = new UserRole(
    1,
    "Designers"
);

$guest = new UserRole(
    2,
    "Guests"
);

$anotherGuest = new UserRole(
    3,
    "Guests"
);

// Check whether our user objects have access to the operation on model object

// Returns false
$acl->isAllowed(
    $designer,
    $customer,
    "search"
);

// Returns true
$acl->isAllowed(
    $guest,
    $customer,
    "search"
);

// Returns false
$acl->isAllowed(
    $anotherGuest,
    $customer,
    "search"
);

You can still add any custom parameters to function and pass associative array in isAllowed() method. Also order doesn’t matter.

角色继承(Roles Inheritance)

我们可以使用 Phalcon\Acl\Role 提供的继承机制来构造更复杂的角色。 Phalcon中的角色可以继承来自其它角色的 权限, 这样就可以实现更巧妙的资源访问控制。 如果要继承权限用户, 我们需要在添加角色函数的第二个参数中写上要继承的那个角色实例。

<?php

use Phalcon\Acl\Role;

// ...

// 创建角色

$roleAdmins = new Role("Administrators", "Super-User role");

$roleGuests = new Role("Guests");

// 添加 "Guests" 到 ACL
$acl->addRole($roleGuests);

// 使Administrators继承Guests的访问权限
$acl->addRole($roleAdmins, $roleGuests);
序列化 ACL 列表(Serializing ACL lists)

为了提高性能, Phalcon\Acl 的实例可以被实例化到APC, session, 文本或数据库中, 这样开发者就不需要重复的 定义acl了。 下面展示了如何去做:

<?php

use Phalcon\Acl\Adapter\Memory as AclList;

// ...

// 检查ACL数据是否存在
if (!is_file("app/security/acl.data")) {
    $acl = new AclList();

    // ... Define roles, resources, access, etc

    // 保存实例化的数据到文本文件中
    file_put_contents(
        "app/security/acl.data",
        serialize($acl)
    );
} else {
    // 返序列化
    $acl = unserialize(
        file_get_contents("app/security/acl.data")
    );
}

// 使用ACL
if ($acl->isAllowed("Guests", "Customers", "edit")) {
    echo "Access granted!";
} else {
    echo "Access denied :(";
}

It’s recommended to use the Memory adapter during development and use one of the other adapters in production.

ACL 事件(ACL Events)

如果需要的话 Phalcon\Acl 可以发送事件到 EventsManager 。 这里我们为acl绑定事件。 其中一些事件的处理结果如果返回了false则表示正在处理的操作会被中止。 支持如下的事件:

事件名 触发条件 能否中止操作
beforeCheckAccess 在权限检查之前触发 Yes
afterCheckAccess 在权限检查之后触发 No

下面的例子中展示了如何绑定事件到此组件:

<?php

use Phalcon\Acl\Adapter\Memory as AclList;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;

// ...

// 创建事件管理器
$eventsManager = new EventsManager();

// 绑定事件类型为acl
$eventsManager->attach(
    "acl:beforeCheckAccess",
    function (Event $event, $acl) {
        echo $acl->getActiveRole();

        echo $acl->getActiveResource();

        echo $acl->getActiveAccess();
    }
);

$acl = new AclList();

// Setup the $acl
// ...

// 绑定eventsManager到ACL组件
$acl->setEventsManager($eventsManager);
自定义适配器(Implementing your own adapters)

开发者要创建自己的扩展或已存在适配器则需要实现此 Phalcon\Acl\AdapterInterface 接口。

多语言支持(Multi-lingual Support)

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.

适配器(Adapters)

This component makes use of adapters to read translation messages from different sources in a unified way.

Adapter Description
Phalcon\Translate\Adapter\NativeArray Uses PHP arrays to store the messages. This is the best option in terms of performance.
组件的使用(Component Usage)

Translation strings are stored in files. The structure of these files could vary depending of the adapter used. Phalcon gives you the freedom to organize your translation strings. A simple structure could be:

app/messages/en.php
app/messages/es.php
app/messages/fr.php
app/messages/zh.php

Each file contains an array of the translations in a key/value manner. For each translation file, keys are unique. The same array is used in different files, where keys remain the same and values contain the translated strings depending on each language.

<?php

// app/messages/en.php
$messages = [
    "hi"      => "Hello",
    "bye"     => "Good Bye",
    "hi-name" => "Hello %name%",
    "song"    => "This song is %song%",
];
<?php

// app/messages/fr.php
$messages = [
    "hi"      => "Bonjour",
    "bye"     => "Au revoir",
    "hi-name" => "Bonjour %name%",
    "song"    => "La chanson est %song%",
];

Implementing the translation mechanism in your application is trivial but depends on how you wish to implement it. You can use an automatic detection of the language from the user’s browser or you can provide a settings page where the user can select their language.

A simple way of detecting the user’s language is to parse the $_SERVER['HTTP_ACCEPT_LANGUAGE'] contents, or if you wish, access it directly by calling $this->request->getBestLanguage() from an action/controller:

<?php

use Phalcon\Mvc\Controller;
use Phalcon\Translate\Adapter\NativeArray;

class UserController extends Controller
{
    protected function getTranslation()
    {
        // Ask browser what is the best language
        $language = $this->request->getBestLanguage();

        $translationFile = "app/messages/" . $language . ".php";

        // Check if we have a translation file for that lang
        if (file_exists($translationFile)) {
            require $translationFile;
        } else {
            // Fallback to some default
            require "app/messages/en.php";
        }

        // Return a translation object
        return new NativeArray(
            [
                "content" => $messages,
            ]
        );
    }

    public function indexAction()
    {
        $this->view->name = "Mike";
        $this->view->t    = $this->getTranslation();
    }
}

The _getTranslation() method is available for all actions that require translations. The $t variable is passed to the views, and with it, we can translate strings in that layer:

<!-- welcome -->
<!-- String: hi => 'Hello' -->
<p><?php echo $t->_("hi"), " ", $name; ?></p>

The _() method is returning the translated string based on the index passed. Some strings need to incorporate placeholders for calculated data i.e. Hello %name%. These placeholders can be replaced with passed parameters in the _() method. The passed parameters are in the form of a key/value array, where the key matches the placeholder name and the value is the actual data to be replaced:

<!-- welcome -->
<!-- String: hi-name => 'Hello %name%' -->
<p><?php echo $t->_("hi-name", ["name" => $name]); ?></p>

Some applications implement multilingual on the URL such as http://www.mozilla.org/es-ES/firefox/. Phalcon can implement this by using a Router.

自定义适配器(Implementing your own adapters)

The Phalcon\Translate\AdapterInterface interface must be implemented in order to create your own translate adapters or extend the existing ones:

<?php

use Phalcon\Translate\AdapterInterface;

class MyTranslateAdapter implements AdapterInterface
{
    /**
     * Adapter constructor
     *
     * @param array $data
     */
    public function __construct($options);

    /**
     * Returns the translation string of the given key
     *
     * @param   string $translateKey
     * @param   array $placeholders
     * @return  string
     */
    public function _($translateKey, $placeholders = null);

    /**
     * Returns the translation related to the given key
     *
     * @param   string $index
     * @param   array $placeholders
     * @return  string
     */
    public function query($index, $placeholders = null);

    /**
     * Check whether is defined a translation key in the internal array
     *
     * @param   string $index
     * @return  bool
     */
    public function exists($index);
}

There are more adapters available for this components in the Phalcon Incubator

Class Autoloader

Phalcon\Loader allows you to load project classes automatically, based on some predefined rules. Since this component is written in C, it provides the lowest overhead in reading and interpreting external PHP files.

The behavior of this component is based on the PHP’s capability of autoloading classes. If a class that does not yet exist is used in any part of the code, a special handler will try to load it. Phalcon\Loader serves as the special handler for this operation. By loading classes on a need-to-load basis, the overall performance is increased since the only file reads that occur are for the files needed. This technique is called lazy initialization.

With this component you can load files from other projects or vendors, this autoloader is PSR-0 and PSR-4 compliant.

Phalcon\Loader offers four options to autoload classes. You can use them one at a time or combine them.

安全层(Security Layer)

Phalcon\Loader offers a security layer sanitizing by default class names avoiding possible inclusion of unauthorized files. Consider the following example:

<?php

// Basic autoloader
spl_autoload_register(
    function ($className) {
        $filepath = $className . ".php";

        if (file_exists($filepath)) {
            require $filepath;
        }
    }
);

The above auto-loader lacks any kind of security. If a function mistakenly launches the auto-loader and a malicious prepared string is used as parameter this would allow to execute any file accessible by the application:

<?php

// This variable is not filtered and comes from an insecure source
$className = "../processes/important-process";

// Check if the class exists triggering the auto-loader
if (class_exists($className)) {
    // ...
}

If ‘../processes/important-process.php’ is a valid file, an external user could execute the file without authorization.

To avoid these or most sophisticated attacks, Phalcon\Loader removes invalid characters from the class name, reducing the possibility of being attacked.

注册命名空间(Registering Namespaces)

If you’re organizing your code using namespaces, or using external libraries which do, the registerNamespaces() method provides the autoloading mechanism. It takes an associative array; the keys are namespace prefixes and their values are directories where the classes are located in. The namespace separator will be replaced by the directory separator when the loader tries to find the classes. Always remember to add a trailing slash at the end of the paths.

<?php

use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some namespaces
$loader->registerNamespaces(
    [
       "Example\Base"    => "vendor/example/base/",
       "Example\Adapter" => "vendor/example/adapter/",
       "Example"         => "vendor/example/",
    ]
);

// Register autoloader
$loader->register();

// The required class will automatically include the
// file vendor/example/adapter/Some.php
$some = new \Example\Adapter\Some();
注册文件夹(Registering Directories)

The third option is to register directories, in which classes could be found. This option is not recommended in terms of performance, since Phalcon will need to perform a significant number of file stats on each folder, looking for the file with the same name as the class. It’s important to register the directories in relevance order. Remember always add a trailing slash at the end of the paths.

<?php

use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some directories
$loader->registerDirs(
    [
        "library/MyComponent/",
        "library/OtherComponent/Other/",
        "vendor/example/adapters/",
        "vendor/example/",
    ]
);

// Register autoloader
$loader->register();

// The required class will automatically include the file from
// the first directory where it has been located
// i.e. library/OtherComponent/Other/Some.php
$some = new \Some();
注册类名(Registering Classes)

The last option is to register the class name and its path. This autoloader can be very useful when the folder convention of the project does not allow for easy retrieval of the file using the path and the class name. This is the fastest method of autoloading. However the more your application grows, the more classes/files need to be added to this autoloader, which will effectively make maintenance of the class list very cumbersome and it is not recommended.

<?php

use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some classes
$loader->registerClasses(
    [
        "Some"         => "library/OtherComponent/Other/Some.php",
        "Example\Base" => "vendor/example/adapters/Example/BaseClass.php",
    ]
);

// Register autoloader
$loader->register();

// Requiring a class will automatically include the file it references
// in the associative array
// i.e. library/OtherComponent/Other/Some.php
$some = new \Some();
Registering Files

You can also registers files that are “non-classes” hence needing a “require”. This is very useful for including files that only have functions:

<?php

use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Register some classes
$loader->registerFiles(
    [
        "functions.php",
        "arrayFunctions.php",
    ]
);

// Register autoloader
$loader->register();

These files are automatically loaded in the register() method.

额外的扩展名(Additional file extensions)

Some autoloading strategies such as “prefixes”, “namespaces” or “directories” automatically append the “php” extension at the end of the checked file. If you are using additional extensions you could set it with the method “setExtensions”. Files are checked in the order as it were defined:

<?php

use Phalcon\Loader;

// Creates the autoloader
$loader = new Loader();

// Set file extensions to check
$loader->setExtensions(
    [
        "php",
        "inc",
        "phb",
    ]
);
修改当前策略(Modifying current strategies)

Additional auto-loading data can be added to existing values by passing “true” as the second parameter:

<?php

// Adding more directories
$loader->registerDirs(
    [
        "../app/library/",
        "../app/plugins/",
    ],
    true
);
自动加载事件(Autoloading Events)

In the following example, the EventsManager is working with the class loader, allowing us to obtain debugging information regarding the flow of operation:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Loader;

$eventsManager = new EventsManager();

$loader = new Loader();

$loader->registerNamespaces(
    [
        "Example\\Base"    => "vendor/example/base/",
        "Example\\Adapter" => "vendor/example/adapter/",
        "Example"          => "vendor/example/",
    ]
);

// Listen all the loader events
$eventsManager->attach(
    "loader:beforeCheckPath",
    function (Event $event, Loader $loader) {
        echo $loader->getCheckedPath();
    }
);

$loader->setEventsManager($eventsManager);

$loader->register();

Some events when returning boolean false could stop the active operation. The following events are supported:

Event Name Triggered Can stop operation?
beforeCheckClass Triggered before starting the autoloading process Yes
pathFound Triggered when the loader locate a class No
afterCheckClass Triggered after finish the autoloading process. If this event is launched the autoloader didn’t find the class file No
注意事项(Troubleshooting)

Some things to keep in mind when using the universal autoloader:

  • Auto-loading process is case-sensitive, the class will be loaded as it is written in the code
  • Strategies based on namespaces/prefixes are faster than the directories strategy
  • If a cache bytecode like APC is installed this will used to retrieve the requested file (an implicit caching of the file is performed)

日志记录(Logging)

Phalcon提供了一个日志记录组件即 Phalcon\Logger。 我们可以使用此组件输出日志到不同的流中,如文件,系统日志等。 这个组件还提供了其它的功能如日志事务(类似于数据库的事务), 配置选项, 还可以输出不同的格式,另外还支持多种过滤器。 Phalcon\Logger 提供了多种日志记录方式,从调试程序到跟踪应用的执行以满足应用的需求。

适配器(Adapters)

此组件使用不同的流适配器来保存日信息。 我们可以按需使用适配器。支持的适配器如下:

适配器 描述
Phalcon\Logger\Adapter\File 保存日志到普通文件
Phalcon\Logger\Adapter\Stream 保存日志到PHP流
Phalcon\Logger\Adapter\Syslog 保存到系统日志
Phalcon\Logger\Adapter\FirePHP 发送日志到FirePHP
创建日志(Creating a Log)

下面的例子展示了如何创建日志对象及如何添加日志信息:

<?php

use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as FileAdapter;

$logger = new FileAdapter("app/logs/test.log");



// These are the different log levels available:

$logger->critical(
    "This is a critical message"
);

$logger->emergency(
    "This is an emergency message"
);

$logger->debug(
    "This is a debug message"
);

$logger->error(
    "This is an error message"
);

$logger->info(
    "This is an info message"
);

$logger->notice(
    "This is a notice message"
);

$logger->warning(
    "This is a warning message"
);

$logger->alert(
    "This is an alert message"
);



// You can also use the log() method with a Logger constant:
$logger->log(
    "This is another error message",
    Logger::ERROR
);

// If no constant is given, DEBUG is assumed.
$logger->log(
    "This is a message"
);

产生的日志信息如下:

[Tue, 28 Jul 15 22:09:02 -0500][CRITICAL] This is a critical message
[Tue, 28 Jul 15 22:09:02 -0500][EMERGENCY] This is an emergency message
[Tue, 28 Jul 15 22:09:02 -0500][DEBUG] This is a debug message
[Tue, 28 Jul 15 22:09:02 -0500][ERROR] This is an error message
[Tue, 28 Jul 15 22:09:02 -0500][INFO] This is an info message
[Tue, 28 Jul 15 22:09:02 -0500][NOTICE] This is a notice message
[Tue, 28 Jul 15 22:09:02 -0500][WARNING] This is a warning message
[Tue, 28 Jul 15 22:09:02 -0500][ALERT] This is an alert message
[Tue, 28 Jul 15 22:09:02 -0500][ERROR] This is another error message
[Tue, 28 Jul 15 22:09:02 -0500][DEBUG] This is a message

You can also set a log level using the setLogLevel() method. This method takes a Logger constant and will only save log messages that are as important or more important than the constant:

<?php

use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as FileAdapter;

$logger = new FileAdapter("app/logs/test.log");

$logger->setLogLevel(
    Logger::CRITICAL
);

In the example above, only critical and emergency messages will get saved to the log. By default, everything is saved.

事务(Transactions)

保存日志到适配器如文件(文件系统)是非常消耗系统资源的。 为了减少应用性能上的开销,我们可以使用日志事务。 事务会把日志记录临时的保存到内存中然后再 写入到适配中(此例子中为文件),(这个操作是个原子操作)

<?php

use Phalcon\Logger\Adapter\File as FileAdapter;

// 生成日志新组件实例
$logger = new FileAdapter("app/logs/test.log");

// 开启事务
$logger->begin();

// 添加消息

$logger->alert(
    "This is an alert"
);

$logger->error(
    "This is another error"
);

//  保存消息到文件中
$logger->commit();
使用多个处理程序进行日志记录(Logging to Multiple Handlers)

Phalcon\Logger 也可以同时保存日志信息到多个适配器中:

<?php

use Phalcon\Logger;
use Phalcon\Logger\Multiple as MultipleStream;
use Phalcon\Logger\Adapter\File as FileAdapter;
use Phalcon\Logger\Adapter\Stream as StreamAdapter;

$logger = new MultipleStream();



$logger->push(
    new FileAdapter("test.log")
);

$logger->push(
    new StreamAdapter("php://stdout")
);



$logger->log(
    "This is a message"
);

$logger->log(
    "This is an error",
    Logger::ERROR
);

$logger->error(
    "This is another error"
);

信息发送的顺序和处理器(适配器)注册的顺序相同。

信息格式(Message Formatting)

此组件使用 formatters 在信息发送前格式化日志信息。 支持下而后格式:

适配器 描述
Phalcon\Logger\Formatter\Line 文本方式格式化信息
Phalcon\Logger\Formatter\Firephp Formats the messages so that they can be sent to FirePHP
Phalcon\Logger\Formatter\Json 使用JSON格式格式化信息
Phalcon\Logger\Formatter\Syslog 使用系统提供的格式格式化信息
行格式化处理(Line Formatter)

使用单行格式格式化信息。 默认的格式如下:

[%date%][%type%] %message%

我们可以使用 setFormat() 来设置自定义格式。 下面是格式变量:

变量 描述
%message% 待记录的日志消息
%date% 消息添加的时间
%type% 消息类型(使用大写)

下面的例子中展示了如何修改日志格式:

<?php

use Phalcon\Logger\Formatter\Line as LineFormatter;

$formatter = new LineFormatter("%date% - %message%");

// 修改日志格式
$logger->setFormatter($formatter);
自定义格式处理(Implementing your own formatters)

若要实现自定义的格式则要实现 Phalcon\Logger\FormatterInterface 接口, 这样才能扩展已有的格式或创建自定义的格式

适配器(Adapters)

下面的例子中展示了每种适配器的简单用法:

数据流日志记录器(Stream Logger)

系统日志保存消息到一个已注册的有效的PHP流中。 这里列出了可用的流: here <http://php.net/manual/en/wrappers.php>`_:

<?php

use Phalcon\Logger\Adapter\Stream as StreamAdapter;

// 使用zlib压缩流
$logger = new StreamAdapter("compress.zlib://week.log.gz");

// 发送消息到stderr
$logger = new StreamAdapter("php://stderr");
文件日志记录器(File Logger)

文件适配器保存所有的日志信息到普通的文件中。 默认情况下日志文件使用添加模式打开,打开文件后文件的指针会指向文件的尾端。 如果文件不存在,则会尝试创建。 我们可以通过传递附加参数的形式来修改打开的模式:

<?php

use Phalcon\Logger\Adapter\File as FileAdapter;

// 使用写模式打开
$logger = new FileAdapter(
    "app/logs/test.log",
    [
        "mode" => "w",
    ]
);
Syslog 日志记录器(Syslog Logger)

使用系统日志适配器。 由于操作系统的不同得到的日志也不尽相同:

<?php

use Phalcon\Logger\Adapter\Syslog as SyslogAdapter;

// 基本用法
$logger = new SyslogAdapter(null);

// Setting ident/mode/facility 参数设置
$logger = new SyslogAdapter(
    "ident-name",
    [
        "option"   => LOG_NDELAY,
        "facility" => LOG_MAIL,
    ]
);
FirePHP 日志记录器(FirePHP Logger)

This logger sends messages in HTTP response headers that are displayed by FirePHP, a Firebug extension for Firefox.

<?php

use Phalcon\Logger;
use Phalcon\Logger\Adapter\Firephp as Firephp;

$logger = new Firephp("");



$logger->log(
    "This is a message"
);

$logger->log(
    "This is an error",
    Logger::ERROR
);

$logger->error(
    "This is another error"
);
自定义适配器(Implementing your own adapters)

如果开发者想自定义新的日志组件则需实现此接口: Phalcon\Logger\AdapterInterface

注释解析器(Annotations Parser)

这是第一个为PHP用C语言写的注释解析器。 Phalcon\Annotations 是一个通用组件,为应用中的PHP类提供易于解析和缓存注释的功能。

注释内容是读自类,方法和属性的注释区域。一个注释单元可以放在注释区域的任何位置。

<?php

/**
 * This is the class description
 *
 * @AmazingClass(true)
 */
class Example
{
    /**
     * This a property with a special feature
     *
     * @SpecialFeature
     */
    protected $someProperty;

    /**
     * This is a method
     *
     * @SpecialFeature
     */
    public function someMethod()
    {
        // ...
    }
}

在上面的例子中,我们发现注释块中除了注释单元,还可以有注释内容,一个注释单元语法如下:

/**
 * @Annotation-Name
 * @Annotation-Name(param1, param2, ...)
 */

当然,一个注释单元可以放在注释内容里的任意位置:

<?php

/**
 * This a property with a special feature
 *
 * @SpecialFeature
 *
 * More comments
 *
 * @AnotherSpecialFeature(true)
 */

这个解析器是高度灵活的,下面这样的注释单元是合法可解析的:

<?php

/**
 * This a property with a special feature @SpecialFeature({
someParameter="the value", false

 })  More comments @AnotherSpecialFeature(true) @MoreAnnotations
 **/

然而,为了使代码更容易维护和理解,我们推荐把注释单元放在注释块的最后:

<?php

/**
 * This a property with a special feature
 * More comments
 *
 * @SpecialFeature({someParameter="the value", false})
 * @AnotherSpecialFeature(true)
 */
读取注释(Reading Annotations)

实现反射器(Reflector)可以轻松获取被定义在类中的注释,使用一个面向对象的接口即可:

<?php

use Phalcon\Annotations\Adapter\Memory as MemoryAdapter;

$reader = new MemoryAdapter();

// 反射在Example类的注释
$reflector = $reader->get("Example");

// 读取类中注释块中的注释
$annotations = $reflector->getClassAnnotations();

// 遍历注释
foreach ($annotations as $annotation) {
    // 打印注释名称
    echo $annotation->getName(), PHP_EOL;

    // 打印注释参数个数
    echo $annotation->numberArguments(), PHP_EOL;

    // 打印注释参数
    print_r($annotation->getArguments());
}

虽然这个注释的读取过程是非常快速的,然而,出于性能原因,我们建议使用一个适配器储存解析后的注释内容。 适配器把处理后的注释内容缓存起来,避免每次读取都需要解析一遍注释。

Phalcon\Annotations\Adapter\Memory 被用在上面的例子中。这个适配器只在请求过程中缓存注释(译者注:请求完成后缓存将被清空),因为这个原因,这个适配器非常适合用于开发环境中。当应用跑在生产环境中还有其他适配器可以替换。

注释类型(Types of Annotations)

注释单元可以有参数也可以没有。参数可以为简单的文字(strings, number, boolean, null),数组,哈希列表或者其他注释单元:

<?php

/**
 * 简单的注释单元
 *
 * @SomeAnnotation
 */

/**
 * 带参数的注释单元
 *
 * @SomeAnnotation("hello", "world", 1, 2, 3, false, true)
 */

/**
 * 带名称限定参数的注释单元
 *
 * @SomeAnnotation(first="hello", second="world", third=1)
 * @SomeAnnotation(first: "hello", second: "world", third: 1)
 */

/**
 * 数组参数
 *
 * @SomeAnnotation([1, 2, 3, 4])
 * @SomeAnnotation({1, 2, 3, 4})
 */

/**
 * 哈希列表参数
 *
 * @SomeAnnotation({first=1, second=2, third=3})
 * @SomeAnnotation({'first'=1, 'second'=2, 'third'=3})
 * @SomeAnnotation({'first': 1, 'second': 2, 'third': 3})
 * @SomeAnnotation(['first': 1, 'second': 2, 'third': 3])
 */

/**
 * 嵌套数组/哈希列表
 *
 * @SomeAnnotation({"name"="SomeName", "other"={
 *     "foo1": "bar1", "foo2": "bar2", {1, 2, 3},
 * }})
 */

/**
 * 嵌套注释单元
 *
 * @SomeAnnotation(first=@AnotherAnnotation(1, 2, 3))
 */
实际使用(Practical Usage)

接下来我们将解释PHP应用程序中的注释的一些实际的例子:

注释开启缓存(Cache Enabler with Annotations)

我们假设一下,假设我们接下来的控制器和开发者想要建一个插件,如果被执行的方法被标记为可缓存的话,这个插件可以自动开启缓存。首先,我们先注册这个插件到Dispatcher服务中,这样这个插件将被通知当控制器的路由被执行的时候:

<?php

use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Manager as EventsManager;

$di["dispatcher"] = function () {
    $eventsManager = new EventsManager();

    // 添加插件到dispatch事件中
    $eventsManager->attach(
        "dispatch",
        new CacheEnablerPlugin()
    );

    $dispatcher = new MvcDispatcher();

    $dispatcher->setEventsManager($eventsManager);

    return $dispatcher;
};

CacheEnablerPlugin 这个插件拦截每一个被dispatcher执行的action,检查如果需要则启动缓存:

<?php

use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\User\Plugin;

/**
 * 为视图启动缓存,如果被执行的action带有@Cache 注释单元。
 */
class CacheEnablerPlugin extends Plugin
{
    /**
     * 这个事件在dispatcher中的每个路由被执行前执行
     */
    public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
    {
        // 解析目前访问的控制的方法的注释
        $annotations = $this->annotations->getMethod(
            $dispatcher->getControllerClass(),
            $dispatcher->getActiveMethod()
        );

        // 检查是否方法中带有注释名称‘Cache’的注释单元
        if ($annotations->has("Cache")) {
            // 这个方法带有‘Cache’注释单元
            $annotation = $annotations->get("Cache");

            // 获取注释单元的‘lifetime’参数
            $lifetime = $annotation->getNamedParameter("lifetime");

            $options = [
                "lifetime" => $lifetime,
            ];

            // 检查注释单元中是否有用户定义的‘key’参数
            if ($annotation->hasNamedParameter("key")) {
                $options["key"] = $annotation->getNamedParameter("key");
            }

            // 为当前dispatcher访问的方法开启cache
            $this->view->cache($options);
        }
    }
}

现在,我们可以使用注释单元在控制器中:

<?php

use Phalcon\Mvc\Controller;

class NewsController extends Controller
{
    public function indexAction()
    {

    }

    /**
     * This is a comment
     *
     * @Cache(lifetime=86400)
     */
    public function showAllAction()
    {
        $this->view->article = Articles::find();
    }

    /**
     * This is a comment
     *
     * @Cache(key="my-key", lifetime=86400)
     */
    public function showAction($slug)
    {
        $this->view->article = Articles::findFirstByTitle($slug);
    }
}
Private/Public areas with Annotations

You can use annotations to tell the ACL which controllers belong to the administrative areas:

<?php

use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Resource;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;

/**
 * This is the security plugin which controls that users only have access to the modules they're assigned to
 */
class SecurityAnnotationsPlugin extends Plugin
{
    /**
     * This action is executed before execute any action in the application
     *
     * @param Event $event
     * @param Dispatcher $dispatcher
     */
    public function beforeDispatch(Event $event, Dispatcher $dispatcher)
    {
        // Possible controller class name
        $controllerName = $dispatcher->getControllerClass();

        // Possible method name
        $actionName = $dispatcher->getActiveMethod();

        // Get annotations in the controller class
        $annotations = $this->annotations->get($controllerName);

        // The controller is private?
        if ($annotations->getClassAnnotations()->has("Private")) {
            // Check if the session variable is active?
            if (!$this->session->get("auth")) {

                // The user is no logged redirect to login
                $dispatcher->forward(
                    [
                        "controller" => "session",
                        "action"     => "login",
                    ]
                );

                return false;
            }
        }

        // Continue normally
        return true;
    }
}
注释适配器(Annotations Adapters)

这些组件利用了适配器去缓存或者不缓存已经解析和处理过的注释内容,从而提升了性能或者为开发环境提供了开发/测试的适配器:

Class Description
Phalcon\Annotations\Adapter\Memory 这个注释只缓存在内存中。当请求结束时缓存将被清空,每次请求都重新解析注释内容. 这个适配器适合用于开发环境中
Phalcon\Annotations\Adapter\Files 已解析和已处理的注释将被永久保存在PHP文件中提高性能。这个适配器必须和字节码缓存一起使用。
Phalcon\Annotations\Adapter\Apc 已解析和已处理的注释将永久保存在APC缓存中提升性能。 这是一个速度非常快的适配器。
Phalcon\Annotations\Adapter\Xcache 已解析和已处理的注释将永久保存在XCache缓存中提升性能. 这也是一个速度非常快的适配器。
自定义适配器(Implementing your own adapters)

为了建立自己的注释适配器或者继承一个已存在的适配器,这个 Phalcon\Annotations\AdapterInterface 接口都必须实现。

命令行应用(Command Line Applications)

CLI应用即是运行在命令行窗体上的应用。 主要用来实现后台任务, 命令行工具等。

结构(Structure)

最小结构的CLI程序如下:

  • app/config/config.php
  • app/tasks/MainTask.php
  • app/cli.php <– 主要启动文件
创建引导(Creating a Bootstrap)

普通的MVC程序中,启动文件用来启动整个应用。和web应用不同, 此处应用中我们使用cli.php来作为启动文件。

下面是一个简单的启动文件示例:

<?php

use Phalcon\Di\FactoryDefault\Cli as CliDI;
use Phalcon\Cli\Console as ConsoleApp;
use Phalcon\Loader;



// 使用CLI工厂类作为默认的服务容器
$di = new CliDI();



/**
 * 注册类自动加载器
 */
$loader = new Loader();

$loader->registerDirs(
    [
        __DIR__ . "/tasks",
    ]
);

$loader->register();



// 加载配置文件(如果存在)

$configFile = __DIR__ . "/config/config.php";

if (is_readable($configFile)) {
    $config = include $configFile;

    $di->set("config", $config);
}



// 创建console应用
$console = new ConsoleApp();

$console->setDI($di);



/**
 * 处理console应用参数
 */
$arguments = [];

foreach ($argv as $k => $arg) {
    if ($k === 1) {
        $arguments["task"] = $arg;
    } elseif ($k === 2) {
        $arguments["action"] = $arg;
    } elseif ($k >= 3) {
        $arguments["params"][] = $arg;
    }
}



try {
    // 处理参数
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();

    exit(255);
}

上面的代码可以使用如下方式执行:

$ php app/cli.php

这样程序会直接执行默认的任务及默认动作.
任务(Tasks)

这里的任务同于web应用中的控制器。 任一 CLI 应用程序都至少包含一个mainTask 及一个 mainAction, 每个任务至少有一个mainAction, 这样在使用者未明确的 指定action时 此mainAction就会执行。

下面即是一个mainTask的例子( app/tasks/MainTask.php ):

<?php

use Phalcon\Cli\Task;

class MainTask extends Task
{
    public function mainAction()
    {
        echo "This is the default task and the default action" . PHP_EOL;
    }
}
处理动作参数(Processing action parameters)

CLI应用中, 开发者也可以在action中处理传递过来的参数, 下面的例子中已经对传递过来的参数进行了处理。

如果你使用下面的参数和动作运行应用程序:

<?php

use Phalcon\Cli\Task;

class MainTask extends Task
{
    public function mainAction()
    {
        echo "This is the default task and the default action" . PHP_EOL;
    }

    /**
     * @param array $params
     */
    public function testAction(array $params)
    {
        echo sprintf(
            "hello %s",
            $params[0]
        );

        echo PHP_EOL;

        echo sprintf(
            "best regards, %s",
            $params[1]
        );

        echo PHP_EOL;
    }
}

我们可以使用下面的命令行及参数执行程序:

$ php app/cli.php main test world universe

hello world
best regards, universe
链中运行任务(Running tasks in a chain)

CLI应用中可以在一个action中执行另一action. 要实现这个需要在 DI 中设置console.

<?php

$di->setShared("console", $console);

try {
    // Handle incoming arguments
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();

    exit(255);
}

然后开发者即可在一个action中使用用其它的action了. 下面即是例子:

<?php

use Phalcon\Cli\Task;

class MainTask extends Task
{
    public function mainAction()
    {
        echo "This is the default task and the default action" . PHP_EOL;

        $this->console->handle(
            [
                "task"   => "main",
                "action" => "test",
            ]
        );
    }

    public function testAction()
    {
        echo "I will get printed too!" . PHP_EOL;
    }
}

当然, 通过扩展 Phalcon\Cli\Task 来实现如上操作会是一个更好主意。

Images

Phalcon\Image is the component that allows you to manipulate image files. Multiple operations can be performed on the same image object.

This guide is not intended to be a complete documentation of available methods and their arguments. Please visit the API for a complete reference.
Adapters

This component makes use of adapters to encapsulate specific image manipulator programs. The following image manipulator programs are supported:

Class Description
Phalcon\Image\Adapter\Gd Requires the GD PHP extension.
Phalcon\Image\Adapter\Imagick Requires the ImageMagick PHP extension.
Implementing your own adapters

The Phalcon\Image\AdapterInterface interface must be implemented in order to create your own image adapters or extend the existing ones.

Saving and rendering images

Before we begin with the various features of the image component, it’s worth understanding how to save and render these images.

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// ...

// Overwrite the original image
$image->save();
<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// ...

// Save to 'new-image.jpg'
$image->save("new-image.jpg");

You can also change the format of the image:

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// ...

// Save as a PNG file
$image->save("image.png");

When saving as a JPEG, you can also specify the quality as the second parameter:

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// ...

// Save as a JPEG with 80% quality
$image->save("image.jpg", 80);
Resizing images

There are several modes of resizing:

  • \Phalcon\Image::WIDTH
  • \Phalcon\Image::HEIGHT
  • \Phalcon\Image::NONE
  • \Phalcon\Image::TENSILE
  • \Phalcon\Image::AUTO
  • \Phalcon\Image::INVERSE
  • \Phalcon\Image::PRECISE
\Phalcon\Image::WIDTH

The height will automatically be generated to keep the proportions the same; if you specify a height, it will be ignored.

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->resize(
    300,
    null,
    \Phalcon\Image::WIDTH
);

$image->save("resized-image.jpg");
\Phalcon\Image::HEIGHT

The width will automatically be generated to keep the proportions the same; if you specify a width, it will be ignored.

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->resize(
    null,
    300,
    \Phalcon\Image::HEIGHT
);

$image->save("resized-image.jpg");
\Phalcon\Image::NONE

The NONE constant ignores the original image’s ratio. Neither width and height are required. If a dimension is not specified, the original dimension will be used. If the new proportions differ from the original proportions, the image may be distorted and stretched.

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->resize(
    400,
    200,
    \Phalcon\Image::NONE
);

$image->save("resized-image.jpg");
\Phalcon\Image::TENSILE

Similar to the NONE constant, the TENSILE constant ignores the original image’s ratio. Both width and height are required. If the new proportions differ from the original proportions, the image may be distorted and stretched.

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->resize(
    400,
    200,
    \Phalcon\Image::NONE
);

$image->save("resized-image.jpg");
Cropping images

For example, to get a 100px by 100px square from the centre of the image:

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$width   = 100;
$height  = 100;
$offsetX = (($image->getWidth() - $width) / 2);
$offsetY = (($image->getHeight() - $height) / 2);

$image->crop($width, $height, $offsetX, $offsetY);

$image->save("cropped-image.jpg");
Rotating images
<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// Rotate an image by 90 degrees clockwise
$image->rotate(90);

$image->save("rotated-image.jpg");
Flipping images

You can flip an image horizontally (using the \Phalcon\Image::HORIZONTAL constant) and vertically (using the \Phalcon\Image::VERTICAL constant):

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

// Flip an image horizontally
$image->flip(
    \Phalcon\Image::HORIZONTAL
);

$image->save("flipped-image.jpg");
Sharpening images

The sharpen() method takes a single parameter - an integer between 0 (no effect) and 100 (very sharp):

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->sharpen(50);

$image->save("sharpened-image.jpg");
Adding watermarks to images
<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$watermark = new \Phalcon\Image\Adapter\Gd("me.jpg");

// Put the watermark in the top left corner
$offsetX = 10;
$offsetY = 10;

$opacity = 70;

$image->watermark(
    $watermark,
    $offsetX,
    $offsetY,
    $opacity
);

$image->save("watermarked-image.jpg");

Of course, you can also manipulate the watermarked image before applying it to the main image:

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$watermark = new \Phalcon\Image\Adapter\Gd("me.jpg");

$watermark->resize(100, 100);
$watermark->rotate(90);
$watermark->sharpen(5);

// Put the watermark in the bottom right corner with a 10px margin
$offsetX = ($image->getWidth() - $watermark->getWidth() - 10);
$offsetY = ($image->getHeight() - $watermark->getHeight() - 10);

$opacity = 70;

$image->watermark(
    $watermark,
    $offsetX,
    $offsetY,
    $opacity
);

$image->save("watermarked-image.jpg");
Blurring images

The blur() method takes a single parameter - an integer between 0 (no effect) and 100 (very blurry):

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->blur(50);

$image->save("blurred-image.jpg");
Pixelating images

The pixelate() method takes a single parameter - the higher the integer, the more pixelated the image becomes:

<?php

$image = new \Phalcon\Image\Adapter\Gd("image.jpg");

$image->pixelate(10);

$image->save("pixelated-image.jpg");

队列(Queueing)

Activities like processing videos, resizing images or sending emails aren’t suitable to be executed online or in real time because it may slow the loading time of pages and severely impact the user experience.

The best solution here is to implement background jobs. The web application puts jobs into a queue and which will be processed separately.

While you can find more sophisticated PHP extensions to address queueing in your applications like RabbitMQ; Phalcon provides a client for Beanstalk, a job queueing backend inspired by Memcache. It’s simple, lightweight, and completely specialized for job queueing.

注意

Some of the returns from queue methods require that the module Yaml be installed. Please refer to http://php.net/manual/book.yaml.php for more information. For PHP < 7, Yaml 1.3.0 is acceptable. For PHP >= 7, you will need to use Yaml >= 2.0.0.

将任务加入队列(Putting Jobs into the Queue)

After connecting to Beanstalk you can insert as many jobs as required. You can define the message structure according to the needs of the application:

<?php

use Phalcon\Queue\Beanstalk;

// Connect to the queue
$queue = new Beanstalk(
    [
        "host" => "192.168.0.21",
        "port" => "11300",
    ]
);

// Insert the job in the queue
$queue->put(
    [
        "processVideo" => 4871,
    ]
);

Available connection options are:

Option Description Default
host IP where the beanstalk server is located 127.0.0.1
port Connection port 11300

In the above example we stored a message which will allow a background job to process a video. The message is stored in the queue immediately and does not have a certain time to live.

Additional options as time to run, priority and delay can be passed as second parameter:

<?php

// Insert the job in the queue with options
$queue->put(
    [
        "processVideo" => 4871,
    ],
    [
        "priority" => 250,
        "delay"    => 10,
        "ttr"      => 3600,
    ]
);

The following options are available:

Option Description
priority It’s an integer < 2**32. Jobs with smaller priority values will be scheduled before jobs with larger priorities. The most urgent priority is 0; the least urgent priority is 4,294,967,295.
delay It’s an integer number of seconds to wait before putting the job in the ready queue. The job will be in the “delayed” state during this time.
ttr Time to run – is an integer number of seconds to allow a worker to run this job. This time is counted from the moment a worker reserves this job.

Every job put into the queue returns a “job id” which you can use to track the status of the job:

<?php

$jobId = $queue->put(
    [
        "processVideo" => 4871,
    ]
);
检索信息(Retrieving Messages)

Once a job is placed into the queue, those messages can be consumed by a background worker which will have enough time to complete the task:

<?php

while (($job = $queue->peekReady()) !== false) {
    $message = $job->getBody();

    var_dump($message);

    $job->delete();
}

Jobs must be removed from the queue to avoid double processing. If multiple background jobs workers are implemented, jobs must be “reserved” so other workers don’t re-process them while other workers have them reserved:

<?php

while (($job = $queue->reserve()) !== false) {
    $message = $job->getBody();

    var_dump($message);

    $job->delete();
}

Our client implement a basic set of the features provided by Beanstalkd but enough to allow you to build applications implementing queues.

数据库抽象层(Database Abstraction Layer)

Phalcon\DbPhalcon\Mvc\Model 背后的一个组件,它为框架提供了强大的model层。它是一个完全由C语言写的独立的高级抽象层的数据库系统。

这个组件提供了比传统模式的更容易上手的数据库操作。

这个指引不是一个完整的包含所有方法和它们的参数的文档。 查看完整的文档参考,请访问 API
数据库适配器(Database Adapters)

这个组件利用了这些适配器去封装特定的数据库的详细操作。Phalcon使用 PDO 去连接这些数据库。下面这些是我们支持的数据库引擎:

Class 描述
Phalcon\Db\Adapter\Pdo\Mysql MySQL是这个世界上最多人使用的关系数据库,它作为服务器运行为多用户提供了访问多个数据库的功能。
Phalcon\Db\Adapter\Pdo\Postgresql PostgreSQL是一个强大,开源的关系数据库。它拥有超过15年的积极发展和经过验证的架构,这些已经为它赢得了可靠性、数据完整性、正确性的良好的声誉
Phalcon\Db\Adapter\Pdo\Sqlite SQLite是一个实现一个自包含的,无服务器,零配置,支持事务的SQL数据库引擎的软件库
自定义适配器(Implementing your own adapters)

如果你想创建自己的适配器或者扩展现有的适配器,这个 Phalcon\Db\AdapterInterface 接口必须被实现。

数据库“方言”

Phalcon把每个数据库引擎的具体操作封装成“方言”,这些“方言”提供了提供通用的功能和SQL生成的适配器。 (译者注:这里的“方言”是指Phalcon把一些常用的数据库操作封装成类的方法,例如检查数据库中表是否存在,不再需要麻烦的手动写SQL,可以把调用tableExists方法去查询)

名称 描述
Phalcon\Db\Dialect\Mysql MySQL的具体“方言”
Phalcon\Db\Dialect\Postgresql PostgreSQL的具体“方言”
Phalcon\Db\Dialect\Sqlite SQLite的具体“方言”
自定义“方言”(Implementing your own dialects)

如果你想创建自己的“方言”或者扩展现有的“方言”,你需要实现这个接口: Phalcon\Db\DialectInterface

连接数据库(Connecting to Databases)

为了建立连接,实例化适配器类是必须的。它只接收一个包含连接参数的数组。 下面的例子展示了,传递必要参数和可选项的参数去连接数据库:

<?php

// 必要参数
$config = [
    "host"     => "127.0.0.1",
    "username" => "mike",
    "password" => "sigma",
    "dbname"   => "test_db",
];

// 可选参数
$config["persistent"] = false;

// 创建连接
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
<?php

// 必要参数
$config = [
    "host"     => "localhost",
    "username" => "postgres",
    "password" => "secret1",
    "dbname"   => "template",
];

// 可选参数
$config["schema"] = "public";

// 创建连接
$connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($config);
<?php

// 必要参数
$config = [
    "dbname" => "/path/to/database.db",
];

// 创建连接
$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($config);
设置额外的 PDO 选项(Setting up additional PDO options)

你可以在连接的时候,通过传递’options’参数,设置PDO选项:

<?php

// 带PDO options参数的创建连接
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql(
    [
        "host"     => "localhost",
        "username" => "root",
        "password" => "sigma",
        "dbname"   => "test_db",
        "options"  => [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'",
            PDO::ATTR_CASE               => PDO::CASE_LOWER,
        ]
    ]
);
查找行(Finding Rows)

文档 Phalcon\Db 提供了几种方法去查询行。在这个例子中,SQL语句是必须符合数据库的SQL语法的:

<?php

$sql = "SELECT id, name FROM robots ORDER BY name";

// 发送SQL语句到数据库
$result = $connection->query($sql);

// 打印每个robot名称
while ($robot = $result->fetch()) {
   echo $robot["name"];
}

// 返回一个包含返回结果的数组
$robots = $connection->fetchAll($sql);
foreach ($robots as $robot) {
   echo $robot["name"];
}

// 只返回查询结果的第一条数据
$robot = $connection->fetchOne($sql);

默认情况下,这些调用会建立一个数组,数组中包含以字段名和以数字下标为key的值。你可以改变这种行为通过使用 Phalcon\Db\Result::setFetchMode() 。这个方法接受一个常量值,确定哪些类型的指标是被要求的。

常量 描述
Phalcon\Db::FETCH_NUM 返回一个包含数字下标的数组
Phalcon\Db::FETCH_ASSOC 返回一个包含字段名的数组
Phalcon\Db::FETCH_BOTH 返回一个包含字段名和数字下标的数组
Phalcon\Db::FETCH_OBJ 返回一个对象而不是一个数组
<?php

$sql = "SELECT id, name FROM robots ORDER BY name";
$result = $connection->query($sql);

$result->setFetchMode(Phalcon\Db::FETCH_NUM);
while ($robot = $result->fetch()) {
   echo $robot[0];
}

这个 Phalcon\Db::query() 方法返回一个 Phalcon\Db\Result\Pdo 实例。这些对象封装了凡是涉及到返回的结果集的功能,例如遍历,寻找特定行,计算总行数等等

<?php

$sql = "SELECT id, name FROM robots";
$result = $connection->query($sql);

// 遍历结果集
while ($robot = $result->fetch()) {
   echo $robot["name"];
}

// 获取第三条记录
$result->seek(2);
$robot = $result->fetch();

// 计算结果集的记录数
echo $result->numRows();
绑定参数(Binding Parameters)

Phalcon\Db 中支持绑定参数。虽然使用绑定参数会有很少性能的损失,但是我们鼓励你使用这个方法 去消除(译者注:是消除,不是减少,因为使用参数绑定可以彻底解决SQL注入问题)SQL注入攻击的可能性。 字符串和占位符都支持,就像下面展示的那样,绑定参数可以简单地实现:

<?php

// 用数字占位符绑定参数
$sql    = "SELECT * FROM robots WHERE name = ? ORDER BY name";
$result = $connection->query(
    $sql,
    [
        "Wall-E",
    ]
);

// 用指定的占位符绑定参数
$sql     = "INSERT INTO `robots`(name`, year) VALUES (:name, :year)";
$success = $connection->query(
    $sql,
    [
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

When using numeric placeholders, you will need to define them as integers i.e. 1 or 2. In this case “1” or “2” are considered strings and not numbers, so the placeholder could not be successfully replaced. With any adapter data are automatically escaped using PDO Quote.

This function takes into account the connection charset, so its recommended to define the correct charset in the connection parameters or in your database server configuration, as a wrong charset will produce undesired effects when storing or retrieving data.

Also, you can pass your parameters directly to the execute/query methods. In this case bound parameters are directly passed to PDO:

<?php

// Binding with PDO placeholders
$sql    = "SELECT * FROM robots WHERE name = ? ORDER BY name";
$result = $connection->query(
    $sql,
    [
        1 => "Wall-E",
    ]
);
插入、更新、删除行(Inserting/Updating/Deleting Rows)

去插入,更新或者删除行,你可以使用原生SQL操作,或者使用类中预设的方法

<?php

// 使用原生SQL插入行
$sql     = "INSERT INTO `robots`(`name`, `year`) VALUES ('Astro Boy', 1952)";
$success = $connection->execute($sql);

// 使用带占位符的SQL插入行
$sql     = "INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)";
$success = $connection->execute(
    $sql,
    [
        "Astro Boy",
        1952,
    ]
);

// 使用类中预设的方法插入行
$success = $connection->insert(
    "robots",
    [
        "Astro Boy",
        1952,
    ],
    [
        "name",
        "year",
    ],
);

// 插入数据的另外一种方法
$success = $connection->insertAsDict(
    "robots",
    [
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

// 使用原生SQL更新行
$sql     = "UPDATE `robots` SET `name` = 'Astro boy' WHERE `id` = 101";
$success = $connection->execute($sql);

// 使用带占位符的SQL更新行
$sql     = "UPDATE `robots` SET `name` = ? WHERE `id` = ?";
$success = $connection->execute(
    $sql,
    [
        "Astro Boy",
        101,
    ]
);

// 使用类中预设的方法更新行
$success = $connection->update(
    "robots",
    [
        "name",
    ],
    [
        "New Astro Boy",
    ],
    "id = 101" // Warning! In this case values are not escaped
);

// 更新数据的另外一种方法
$success = $connection->updateAsDict(
    "robots",
    [
        "name" => "New Astro Boy",
    ],
    "id = 101" // Warning! In this case values are not escaped
);

// With escaping conditions
$success = $connection->update(
    "robots",
    [
        "name",
    ],
    [
        "New Astro Boy",
    ],
    [
        "conditions" => "id = ?",
        "bind"       => [101],
        "bindTypes"  => [PDO::PARAM_INT], // Optional parameter
    ]
);
$success = $connection->updateAsDict(
    "robots",
    [
        "name" => "New Astro Boy",
    ],
    [
        "conditions" => "id = ?",
        "bind"       => [101],
        "bindTypes"  => [PDO::PARAM_INT], // Optional parameter
    ]
);

// 使用原生SQL删除数据
$sql     = "DELETE `robots` WHERE `id` = 101";
$success = $connection->execute($sql);

// 使用带占位符的SQL删除行
$sql     = "DELETE `robots` WHERE `id` = ?";
$success = $connection->execute($sql, [101]);

// 使用类中预设的方法删除行
$success = $connection->delete(
    "robots",
    "id = ?",
    [
        101,
    ]
);
事务与嵌套事务(Transactions and Nested Transactions)

PDO支持事务工作。在事务里面执行数据操作, 在大多数数据库系统上, 往往可以提高数据库的性能:

<?php

try {
    // 开始一个事务
    $connection->begin();

    // 执行一些操作
    $connection->execute("DELETE `robots` WHERE `id` = 101");
    $connection->execute("DELETE `robots` WHERE `id` = 102");
    $connection->execute("DELETE `robots` WHERE `id` = 103");

    // 提交操作,如果一切正常
    $connection->commit();
} catch (Exception $e) {
    // 如果发现异常,回滚操作
    $connection->rollback();
}

除了标准的事务, Phalcon\Db 提供了内置支持`嵌套事务`_(如果数据库系统支持的话)。 当你第二次调用begin()方法,一个嵌套的事务就被创建了:

<?php

try {
    // 开始一个事务
    $connection->begin();

    // 执行某些SQL操作
    $connection->execute("DELETE `robots` WHERE `id` = 101");

    try {
        // 开始一个嵌套事务
        $connection->begin();

        // 在嵌套事务中执行这些SQL
        $connection->execute("DELETE `robots` WHERE `id` = 102");
        $connection->execute("DELETE `robots` WHERE `id` = 103");

        // 创建一个保存的点
        $connection->commit();
    } catch (Exception $e) {
        // 发生错误,释放嵌套的事务
        $connection->rollback();
    }

    // 继续,执行更多SQL操作
    $connection->execute("DELETE `robots` WHERE `id` = 104");

    // 如果一切正常,提交
    $connection->commit();
} catch (Exception $e) {
    // 发生错误,回滚操作
    $connection->rollback();
}
数据库事件(Database Events)

Phalcon\Db 可以发送事件到一个 EventsManager 中,如果它存在的话。 一些事件当返回布尔值false可以停止操作。我们支持下面这些事件:

事件名 何时触发 可以停止操作吗?
afterConnect 当成功连接数据库之后触发 No
beforeQuery 在发送SQL到数据库前触发 Yes
afterQuery 在发送SQL到数据库执行后触发 No
beforeDisconnect 在关闭一个暂存的数据库连接前触发 No
beginTransaction 事务启动前触发 No
rollbackTransaction 事务回滚前触发 No
commitTransaction 事务提交前触发 No

绑定一个EventsManager给一个连接是很简单的, Phalcon\Db 将触发这些类型为“db”的事件:

<?php

use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as Connection;

$eventsManager = new EventsManager();

// 监听所有数据库事件
$eventsManager->attach('db', $dbListener);

$connection = new Connection(
    [
        "host"     => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname"   => "invo",
    ]
);

// 把eventsManager分配给适配器实例
$connection->setEventsManager($eventsManager);

数据库事件中,停止操作是非常有用的,例如:如果你想要实现一个注入检查器,在发送SQL到数据库前触发:

<?php

use Phalcon\Events\Event;

$eventsManager->attach(
    "db:beforeQuery",
    function (Event $event, $connection) {
        $sql = $connection->getSQLStatement();

        // 检查是否有恶意关键词
        if (preg_match("/DROP|ALTER/i", $sql)) {
            // DROP/ALTER 操作是不允许的, 这肯定是一个注入!
            // 返回false中断此操作
            return false;
        }

        // 一切正常
        return true;
    }
);
分析 SQL 语句(Profiling SQL Statements)

Phalcon\Db 包含了一个性能分析组件,叫 Phalcon\Db\Profiler ,它被用于分析数据库的操作性能以便诊断性能问题,并发现瓶颈。 使用 Phalcon\Db\Profiler 来分析数据库真的很简单:

<?php

use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Profiler as DbProfiler;

$eventsManager = new EventsManager();

$profiler = new DbProfiler();

// 监听所有数据库的事件
$eventsManager->attach(
    "db",
    function (Event $event, $connection) use ($profiler) {
        if ($event->getType() === "beforeQuery") {
            $sql = $connection->getSQLStatement();

            // 操作前启动分析
            $profiler->startProfile($sql);
        }

        if ($event->getType() === "afterQuery") {
            // 操作后停止分析
            $profiler->stopProfile();
        }
    }
);

// 设置事件管理器
$connection->setEventsManager($eventsManager);

$sql = "SELECT buyer_name, quantity, product_name "
     . "FROM buyers "
     . "LEFT JOIN products ON buyers.pid = products.id";

// 执行SQL
$connection->query($sql);

// 获取最后一个分析结果
$profile = $profiler->getLastProfile();

echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";

你也可以基于 Phalcon\Db\Profiler 建立你自己的分析器类,以记录SQL语句发送到数据库的实时统计:

<?php

use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Profiler as Profiler;
use Phalcon\Db\Profiler\Item as Item;

class DbProfiler extends Profiler
{
    /**
     * 在SQL语句将要发送给数据库前执行
     */
    public function beforeStartProfile(Item $profile)
    {
        echo $profile->getSQLStatement();
    }

    /**
     * 在SQL语句已经被发送到数据库后执行
     */
    public function afterEndProfile(Item $profile)
    {
        echo $profile->getTotalElapsedSeconds();
    }
}

// 创建一个事件管理器
$eventsManager = new EventsManager();

// 创建一个监听器
$dbProfiler = new DbProfiler();

// 设置监听器监听所有的数据库事件
$eventsManager->attach("db", $dbProfiler);
记录 SQL 语句(Logging SQL Statements)

使用例如 Phalcon\Db 的高级抽象组件操作数据库,被发送到数据库中执行的原生SQL语句是难以获知的。使用 Phalcon\LoggerPhalcon\Db 来配合使用,可以在数据库抽象层上提供记录的功能。

<?php

use Phalcon\Logger;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Logger\Adapter\File as FileLogger;

$eventsManager = new EventsManager();

$logger = new FileLogger("app/logs/db.log");

$eventsManager->attach(
    "db:beforeQuery",
    function (Event $event, $connection) use ($logger) {
        $sql = $connection->getSQLStatement();

        $logger->log($sql, Logger::INFO);
    }
);

// 设置事件管理器
$connection->setEventsManager($eventsManager);

// 执行一些SQL
$connection->insert(
    "products",
    [
        "Hot pepper",
        3.50,
    ],
    [
        "name",
        "price",
    ]
);

如上操作,文件 app/logs/db.log 将包含像下面这样的信息:

[Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products
(name, price) VALUES ('Hot pepper', 3.50)
自定义日志记录器(Implementing your own Logger)

你可以实现你自己的日志类来记录数据库的所有操作,通过创建一个实现了”log”方法的类。 这个方法需要接受一个字符串作为第一个参数。你可以把日志类的对象传递给 Phalcon\Db::setLogger(), 这样执行SQL时将调用这个对象的log方法去记录。

获取数据库表与视图信息(Describing Tables/Views)

Phalcon\Db 也提供了方法去检索详细的表和视图信息:

<?php

// 获取test_db数据库的所有表
$tables = $connection->listTables("test_db");

// 在数据库中是否存在'robots'这个表
$exists = $connection->tableExists("robots");

// 获取'robots'字段名称,数据类型,特殊特征
$fields = $connection->describeColumns("robots");
foreach ($fields as $field) {
    echo "Column Type: ", $field["Type"];
}

// 获取'robots'表的所有索引
$indexes = $connection->describeIndexes("robots");
foreach ($indexes as $index) {
    print_r(
        $index->getColumns()
    );
}

// 获取'robots'表的所有外键
$references = $connection->describeReferences("robots");
foreach ($references as $reference) {
    // 打印引用的列
    print_r(
        $reference->getReferencedColumns()
    );
}

一个表的详细描述信息和MYSQL的describe命令返回的信息非常相似,它包含以下信息:

下标 描述
Field 字段名称
Type 字段类型
Key 是否是主键或者索引
Null 是否允许为空

对于被支持的数据库系统,获取视图的信息的方法也被实现了:

<?php

// 获取test_db数据库的视图
$tables = $connection->listViews("test_db");

// 'robots'视图是否存在数据库中
$exists = $connection->viewExists("robots");
创建/修改/删除表

不同的数据库系统(MySQL,Postgresql等)通过了CREATE, ALTER 或 DROP命令提供了用于创建,修改或删除表的功能。但是不同的数据库语法不同。 Phalcon\Db 提供了统一的接口来改变表,而不需要区分基于目标存储系统上的SQL语法。

创建数据库表(Creating Tables)

下面这个例子展示了怎么建立一个表:

<?php

use \Phalcon\Db\Column as Column;

$connection->createTable(
    "robots",
    null,
    [
       "columns" => [
            new Column(
                "id",
                [
                    "type"          => Column::TYPE_INTEGER,
                    "size"          => 10,
                    "notNull"       => true,
                    "autoIncrement" => true,
                    "primary"       => true,
                ]
            ),
            new Column(
                "name",
                [
                    "type"    => Column::TYPE_VARCHAR,
                    "size"    => 70,
                    "notNull" => true,
                ]
            ),
            new Column(
                "year",
                [
                    "type"    => Column::TYPE_INTEGER,
                    "size"    => 11,
                    "notNull" => true,
                ]
            ),
        ]
    ]
);

Phalcon\Db::createTable() 接受一个描述数据库表相关的数组。字段被定义成class Phalcon\Db\Column 。 下表列出了可用于定义字段的选项:

选项 描述 是否可选
“type” 字段类型,传入的值必须是 Phalcon\Db\Column 的常量值(看下面的列表)
“primary” True的话表示列是表主键的一部分
“size” 字段的大小,像VARCHAR或者INTEGER类型需要用到
“scale” 指定字段存放多少位小数,DECIMAL或者NUMBER类型时需要用到
“unsigned” 是否有符号,INTEGER列可能需要设置是否有符号,该选项不适用于其他类型的列
“notNull” 字段是否可以储存null值(即是否为空)
“default” Default value (when used with "notNull" => true).
“autoIncrement” 字段是否自增,设置了这个属性将自动填充自增整数,一个表只能设置一个列为自增属性
“bind” 字段类型绑定, BIND_TYPE_* 常量告诉数据库在保存数据前怎么绑定数据类型
“first” 把字段设置为表的第一位
“after” 设置字段放在指定字段的后面

Phalcon\Db 支持下面的数据库字段类型:

  • Phalcon\Db\Column::TYPE_INTEGER
  • Phalcon\Db\Column::TYPE_DATE
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_TEXT

传入 Phalcon\Db::createTable() 的相关数组可能含有的下标:

下标 描述 是否可选
“columns” 一个数组包含表的所有字段,字段要定义成 Phalcon\Db\Column
“indexes” 一个数组包含表的所有索引,索引要定义成 Phalcon\Db\Index
“references” 一个数组包含表的所有外键,外键要定义成 Phalcon\Db\Reference
“options” 一个表包含所有创建的选项. 这些选项常常和数据库迁移有关.
修改数据库表(Altering Tables)

随着你的应用的增长,作为一个重构的一部分,或者增加新功能,你也许需要修改你的数据库。 因为不是所有的数据库允许你修改已存在的字段或者添加字段在2个已存在的字段之间。所以 Phalcon\Db 会受到数据库系统的这些限制。

<?php

use Phalcon\Db\Column as Column;

// 添加一个新的字段
$connection->addColumn(
    "robots",
    null,
    new Column(
        "robot_type",
        [
            "type"    => Column::TYPE_VARCHAR,
            "size"    => 32,
            "notNull" => true,
            "after"   => "name",
        ]
    )
);

// 修改一个已存在的字段
$connection->modifyColumn(
    "robots",
    null,
    new Column(
        "name",
        [
            "type"    => Column::TYPE_VARCHAR,
            "size"    => 40,
            "notNull" => true,
        ]
    )
);

// 删除名为"name"的字段
$connection->dropColumn(
    "robots",
    null,
    "name"
);
删除数据库表(Dropping Tables)

删除数据库表的例子:

<?php

// 删除'robots'表
$connection->dropTable("robots");

// 删除数据库'machines'中的'robots'表
$connection->dropTable("robots", "machines");

国际化(Internationalization)

Phalcon is written in C as an extension for PHP. There is a PECL extension that offers internationalization functions to PHP applications called intl. Starting from PHP 5.4/5.5 this extension is bundled with PHP. Its documentation can be found in the pages of the official PHP manual.

Phalcon does not offer this functionality, since creating such a component would be replicating existing code.

In the examples below, we will show you how to implement the intl extension’s functionality into Phalcon powered applications.

This guide is not intended to be a complete documentation of the intl extension. Please visit its the documentation of the extension for a reference.
匹配最佳的区域设置(Find out best available Locale)

There are several ways to find out the best available locale using intl. One of them is to check the HTTP “Accept-Language” header:

<?php

$locale = Locale::acceptFromHttp($_SERVER["HTTP_ACCEPT_LANGUAGE"]);

// Locale could be something like "en_GB" or "en"
echo $locale;

Below method returns a locale identified. It is used to get language, culture, or regionally-specific behavior from the Locale API.

Examples of identifiers include:

  • en-US (English, United States)
  • ru-RU (Russian, Russia)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)
基于区域设置格式化信息(Formatting messages based on Locale)

Part of creating a localized application is to produce concatenated, language-neutral messages. The MessageFormatter allows for the production of those messages.

Printing numbers formatted based on some locale:

<?php

// Prints € 4 560
$formatter = new MessageFormatter("fr_FR", "€ {0, number, integer}");
echo $formatter->format([4560]);

// Prints USD$ 4,560.5
$formatter = new MessageFormatter("en_US", "USD$ {0, number}");
echo $formatter->format([4560.50]);

// Prints ARS$ 1.250,25
$formatter = new MessageFormatter("es_AR", "ARS$ {0, number}");
echo $formatter->format([1250.25]);

Message formatting using time and date patterns:

<?php

// Setting parameters
$time   = time();
$values = [7, $time, $time];

// Prints "At 3:50:31 PM on Apr 19, 2015, there was a disturbance on planet 7."
$pattern   = "At {1, time} on {1, date}, there was a disturbance on planet {0, number}.";
$formatter = new MessageFormatter("en_US", $pattern);
echo $formatter->format($values);

// Prints "À 15:53:01 le 19 avr. 2015, il y avait une perturbation sur la planète 7."
$pattern   = "À {1, time} le {1, date}, il y avait une perturbation sur la planète {0, number}.";
$formatter = new MessageFormatter("fr_FR", $pattern);
echo $formatter->format($values);
特定区域设置的字符串比较(Locale-Sensitive comparison)

The Collator class provides string comparison capability with support for appropriate locale-sensitive sort orderings. Check the examples below on the usage of this class:

<?php

// Create a collator using Spanish locale
$collator = new Collator("es");

// Returns that the strings are equal, in spite of the emphasis on the "o"
$collator->setStrength(Collator::PRIMARY);
var_dump($collator->compare("una canción", "una cancion"));

// Returns that the strings are not equal
$collator->setStrength(Collator::DEFAULT_VALUE);
var_dump($collator->compare("una canción", "una cancion"));
音译(Transliteration)

Transliterator provides transliteration of strings:

<?php

$id = "Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();";
$transliterator = Transliterator::create($id);

$string = "garçon-étudiant-où-L'école";
echo $transliterator->transliterate($string); // garconetudiantoulecole

数据库迁移(Database Migrations)

Migrations are a convenient way for you to alter your database in a structured and organized manner.

Important: Migrations are available in Phalcon Developer Tools You need at least Phalcon Framework version 0.5.0 to use developer tools. Also, it is recommended to have PHP 5.4 or greater installed.

Often in development we need to update changes in production environments. Some of these changes could be database modifications like new fields, new tables, removing indexes, etc.

When a migration is generated a set of classes are created to describe how your database is structured at that particular moment. These classes can be used to synchronize the schema structure on remote databases setting your database ready to work with the new changes that your application implements. Migrations describe these transformations using plain PHP.

图解导出(Schema Dumping)

The Phalcon Developer Tools provides scripts to manage migrations (generation, running and rollback).

The available options for generating migrations are:

_images/migrations-1.png

Running this script without any parameters will simply dump every object (tables and views) from your database into migration classes.

Each migration has a version identifier associated with it. The version number allows us to identify if the migration is newer or older than the current ‘version’ of our database. Versions will also inform Phalcon of the running order when executing a migration.

_images/migrations-2.png

When a migration is generated, instructions are displayed on the console to describe the different steps of the migration and the execution time of those statements. At the end, a migration version is generated.

By default Phalcon Developer Tools uses the app/migrations directory to dump the migration files. You can change the location by setting one of the parameters on the generation script. Each table in the database has its respective class generated in a separated file under a directory referring its version:

_images/migrations-3.png
迁移类剖析(Migration Class Anatomy)

Each file contains a unique class that extends the Phalcon\Mvc\Model\Migration class. These classes normally have two methods: up() and down(). up() performs the migration, while down() rolls it back.

up() also contains the magic method morphTable(). The magic comes when it recognizes the changes needed to synchronize the actual table in the database to the description given.

<?php

use Phalcon\Db\Column as Column;
use Phalcon\Db\Index as Index;
use Phalcon\Db\Reference as Reference;
use Phalcon\Mvc\Model\Migration;

class ProductsMigration_100 extends Migration
{
    public function up()
    {
        $this->morphTable(
            "products",
            [
                "columns" => [
                    new Column(
                        "id",
                        [
                            "type"          => Column::TYPE_INTEGER,
                            "size"          => 10,
                            "unsigned"      => true,
                            "notNull"       => true,
                            "autoIncrement" => true,
                            "first"         => true,
                        ]
                    ),
                    new Column(
                        "product_types_id",
                        [
                            "type"     => Column::TYPE_INTEGER,
                            "size"     => 10,
                            "unsigned" => true,
                            "notNull"  => true,
                            "after"    => "id",
                        ]
                    ),
                    new Column(
                        "name",
                        [
                            "type"    => Column::TYPE_VARCHAR,
                            "size"    => 70,
                            "notNull" => true,
                            "after"   => "product_types_id",
                        ]
                    ),
                    new Column(
                        "price",
                        [
                            "type"    => Column::TYPE_DECIMAL,
                            "size"    => 16,
                            "scale"   => 2,
                            "notNull" => true,
                            "after"   => "name",
                        ]
                    ),
                ],
                "indexes" => [
                    new Index(
                        "PRIMARY",
                        [
                            "id",
                        ]
                    ),
                    new Index(
                        "product_types_id",
                        [
                            "product_types_id",
                        ],
                    ),
                ],
                "references" => [
                    new Reference(
                        "products_ibfk_1",
                        [
                            "referencedSchema"  => "invo",
                            "referencedTable"   => "product_types",
                            "columns"           => ["product_types_id"],
                            "referencedColumns" => ["id"],
                        ]
                    ),
                ],
                "options" => [
                    "TABLE_TYPE"      => "BASE TABLE",
                    "ENGINE"          => "InnoDB",
                    "TABLE_COLLATION" => "utf8_general_ci",
                ],
            ]
        );
    }
}

The class is called “ProductsMigration_100”. Suffix 100 refers to the version 1.0.0. morphTable() receives an associative array with 4 possible sections:

Index Description Optional
“columns” An array with a set of table columns No
“indexes” An array with a set of table indexes. Yes
“references” An array with a set of table references (foreign keys). Yes
“options” An array with a set of table creation options. These options are often related to the database system in which the migration was generated. Yes
定义列(Defining Columns)

Phalcon\Db\Column is used to define table columns. It encapsulates a wide variety of column related features. Its constructor receives as first parameter the column name and an array describing the column. The following options are available when describing columns:

Option Description Optional
“type” Column type. Must be a Phalcon_Db_Column constant (see below) No
“size” Some type of columns like VARCHAR or INTEGER may have a specific size Yes
“scale” DECIMAL or NUMBER columns may be have a scale to specify how much decimals it must store Yes
“unsigned” INTEGER columns may be signed or unsigned. This option does not apply to other types of columns Yes
“notNull” Column can store null values? Yes
“autoIncrement” With this attribute column will filled automatically with an auto-increment integer. Only one column in the table can have this attribute. Yes
“first” Column must be placed at first position in the column order Yes
“after” Column must be placed after indicated column Yes

Database migrations support the following database column types:

  • Phalcon\Db\Column::TYPE_INTEGER
  • Phalcon\Db\Column::TYPE_VARCHAR
  • Phalcon\Db\Column::TYPE_CHAR
  • Phalcon\Db\Column::TYPE_DATE
  • Phalcon\Db\Column::TYPE_DATETIME
  • Phalcon\Db\Column::TYPE_TIMESTAMP
  • Phalcon\Db\Column::TYPE_DECIMAL
  • Phalcon\Db\Column::TYPE_TEXT
  • Phalcon\Db\Column::TYPE_BOOLEAN
  • Phalcon\Db\Column::TYPE_FLOAT
  • Phalcon\Db\Column::TYPE_DOUBLE
  • Phalcon\Db\Column::TYPE_TINYBLOB
  • Phalcon\Db\Column::TYPE_BLOB
  • Phalcon\Db\Column::TYPE_MEDIUMBLOB
  • Phalcon\Db\Column::TYPE_LONGBLOB
  • Phalcon\Db\Column::TYPE_JSON
  • Phalcon\Db\Column::TYPE_JSONB
  • Phalcon\Db\Column::TYPE_BIGINTEGER
定义索引(Defining Indexes)

Phalcon\Db\Index defines table indexes. An index only requires that you define a name for it and a list of its columns. Note that if any index has the name PRIMARY, Phalcon will create a primary key index for that table.

定义关系(Defining References)

Phalcon\Db\Reference defines table references (also called foreign keys). The following options can be used to define a reference:

Index Description Optional Implemented in
“referencedTable” It’s auto-descriptive. It refers to the name of the referenced table. No All
“columns” An array with the name of the columns at the table that have the reference No All
“referencedColumns” An array with the name of the columns at the referenced table No All
“referencedSchema” The referenced table maybe is on another schema or database. This option allows you to define that. Yes All
“onDelete” If the foreign record is removed, perform this action on the local record(s). Yes MySQL PostgreSQL
“onUpdate” If the foreign record is updated, perform this action on the local record(s). Yes MySQL PostgreSQL
创建迁移类(Writing Migrations)

Migrations aren’t only designed to “morph” table. A migration is just a regular PHP class so you’re not limited to these functions. For example after adding a column you could write code to set the value of that column for existing records. For more details and examples of individual methods, check the database component.

<?php

use Phalcon\Mvc\Model\Migration;

class ProductsMigration_100 extends Migration
{
    public function up()
    {
        // ...

        self::$_connection->insert(
            "products",
            [
                "Malabar spinach",
                14.50,
            ],
            [
                "name",
                "price",
            ]
        );
    }
}
执行迁移(Running Migrations)

Once the generated migrations are uploaded on the target server, you can easily run them as shown in the following example:

_images/migrations-4.png
_images/migrations-5.png

Depending on how outdated is the database with respect to migrations, Phalcon may run multiple migration versions in the same migration process. If you specify a target version, Phalcon will run the required migrations until it reaches the specified version.

调试应用程序(Debugging Applications)

_images/xdebug-1.jpg

Phalcon中提供了提供了几种调试级别即通知,错误和异常。 异常类 Exception class 提供了错误发生时的一些常用的调试信息如文件,行,消息,错误代码,跟踪信息等。 Phalcon主要使用这个异常类来包装这些功能,以方便开发者或用户使用。

尽管Phalcon是使用C语言书写的,但其依然如其它的PHP框架般提供了一些必须的调试工具,PHP本身提供的调试工具亦然可以正常使用。

捕获异常(Catching Exceptions)

纵观Phalcon的文档及其提供的例子程序, 有一个最直接的捕获异常的方法即是使用try/catch块:

<?php

try {

    // ... Some Phalcon/PHP code

} catch (\Exception $e) {

}

try/catch块内发生的异常会被捕获然后放入 $e 变量。 开发者可以使用 Phalcon\Exception (扩展自 Exception class )来确定异常信息是来自Phalcon还是PHP本身。 PHP产生的所有异常都是基于 Exception class , 且至少含有如下元素:

<?php

class Exception
{

    /* Properties */
    protected string $message;
    protected int $code;
    protected string $file;
    protected int $line;

    /* Methods */
    public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]])
    final public string getMessage ( void )
    final public Exception getPrevious ( void )
    final public mixed getCode ( void )
    final public string getFile ( void )
    final public int getLine ( void )
    final public array getTrace ( void )
    final public string getTraceAsString ( void )
    public string __toString ( void )
    final private void __clone ( void )
}

如从 Exception class 中取得异常信息一样, 我也可以从 Phalcon\Exception 中取异常信息。

<?php

try {

    // ... App code ...

} catch (\Exception $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
    echo " File=", $e->getFile(), "\n";
    echo " Line=", $e->getLine(), "\n";
    echo $e->getTraceAsString();
}

因此, 开发者可以非常容易找出在哪个文件中哪一行产生的异常信息,也可以看到异常信息涉及到的模块:

PDOException: SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost'
    (using password: NO)
 File=/Applications/MAMP/htdocs/invo/public/index.php
 Line=74
#0 [internal function]: PDO->__construct('mysql:host=loca...', 'root', '', Array)
#1 [internal function]: Phalcon\Db\Adapter\Pdo->connect(Array)
#2 /Applications/MAMP/htdocs/invo/public/index.php(74):
    Phalcon\Db\Adapter\Pdo->__construct(Array)
#3 [internal function]: {closure}()
#4 [internal function]: call_user_func_array(Object(Closure), Array)
#5 [internal function]: Phalcon\Di->_factory(Object(Closure), Array)
#6 [internal function]: Phalcon\Di->get('db', Array)
#7 [internal function]: Phalcon\Di->getShared('db')
#8 [internal function]: Phalcon\Mvc\Model->getConnection()
#9 [internal function]: Phalcon\Mvc\Model::_getOrCreateResultset('Users', Array, true)
#10 /Applications/MAMP/htdocs/invo/app/controllers/SessionController.php(83):
    Phalcon\Mvc\Model::findFirst('email='demo@pha...')
#11 [internal function]: SessionController->startAction()
#12 [internal function]: call_user_func_array(Array, Array)
#13 [internal function]: Phalcon\Mvc\Dispatcher->dispatch()
#14 /Applications/MAMP/htdocs/invo/public/index.php(114): Phalcon\Mvc\Application->handle()
#15 {main}

从上面我们可以看到异常信息中有Phalcon的类及方法,甚至调用时的参数也显示了出来。 如果需要可以使用 Exception::getTrace 获取更多的信息。

调试组件(Debug component)

Phalcon提供的调试组件可以使开发者更容易的定位代码中的错误。

下面的视频中展示了如何工作的:

要打开调试功能只需要如下做:

<?php

$debug = new \Phalcon\Debug();
$debug->listen();

注意一定要去掉Try/Catch块才可以, 否则异常信息不会正确的输出(事实上很多时候Phalco显示异常信息是非常耗时的)。

反射与内省(Reflection and Introspection)

Phalcon的类的实例通常比一般的类实例更复杂。 这里我们可以使用 ‘Reflection API’_ (反射机制) 或 直接打印其内部状态来观其究竟:

<?php

$router = new Phalcon\Mvc\Router();
print_r($router);

开发者可以非常容易的观察到对象内部的状态。 上面的代码输出如下:

Phalcon\Mvc\Router Object
(
    [_dependencyInjector:protected] =>
    [_module:protected] =>
    [_controller:protected] =>
    [_action:protected] =>
    [_params:protected] => Array
        (
        )
    [_routes:protected] => Array
        (
            [0] => Phalcon\Mvc\Router\Route Object
                (
                    [_pattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$#
                    [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)[/]{0,1}$#
                    [_paths:protected] => Array
                        (
                            [controller] => 1
                        )

                    [_methods:protected] =>
                    [_id:protected] => 0
                    [_name:protected] =>
                )

            [1] => Phalcon\Mvc\Router\Route Object
                (
                    [_pattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$#
                    [_compiledPattern:protected] => #^/([a-zA-Z0-9\_]+)/([a-zA-Z0-9\_]+)(/.*)*$#
                    [_paths:protected] => Array
                        (
                            [controller] => 1
                            [action] => 2
                            [params] => 3
                        )
                    [_methods:protected] =>
                    [_id:protected] => 1
                    [_name:protected] =>
                )
        )
    [_matchedRoute:protected] =>
    [_matches:protected] =>
    [_wasMatched:protected] =>
    [_defaultModule:protected] =>
    [_defaultController:protected] =>
    [_defaultAction:protected] =>
    [_defaultParams:protected] => Array
        (
        )
)
使用 XDebug(Using XDebug)

XDebug 是一个非常好(神奇)的调试工具,其和PHP内部调试工具一起为我们提调试工具(可以和PHP内置的调试工具互补)。 XDebug 也是一个PHP扩展, 所以二者可以一起使用,而且不需要额外的配置。

下面的视频中展示了Phalcon中使用XDebug的情况:

一旦安装了xdebug, 开发者便可以使用其API来取得更多的异常信息和其它信息:

我们强烈推荐至少使用XDebug 2.2.3 以提供与Phalcon最佳的兼容性。

下面的例子中调用了 xdebug_print_function_stack 方法, 并返回了该方法产生的代码跟踪结果:

<?php

use Phalcon\Mvc\Controller;

class SignupController extends Controller
{
    public function indexAction()
    {

    }

    public function registerAction()
    {
        // Request variables from HTML form
        $name  = $this->request->getPost("name", "string");
        $email = $this->request->getPost("email", "email");

        // Stop execution and show a backtrace
        return xdebug_print_function_stack("stop here!");

        $user        = new Users();
        $user->name  = $name;
        $user->email = $email;

        // Store and check for errors
        $user->save();
    }
}

这个例子中, XDebug显示出了局部变量和代码的跟踪信息:

Xdebug: stop here! in /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php
    on line 19

Call Stack:
    0.0383     654600   1. {main}() /Applications/MAMP/htdocs/tutorial/public/index.php:0
    0.0392     663864   2. Phalcon\Mvc\Application->handle()
        /Applications/MAMP/htdocs/tutorial/public/index.php:37
    0.0418     738848   3. SignupController->registerAction()
        /Applications/MAMP/htdocs/tutorial/public/index.php:0
    0.0419     740144   4. xdebug_print_function_stack()
        /Applications/MAMP/htdocs/tutorial/app/controllers/SignupController.php:19

使用xdebug我们可以使用若干种方法来取得关phalcon应用的调试信息。更多信可以参看这里的 XDebug documentation ( XDebug 文档)。

单元测试(Unit testing)

适当的测试有帮于更好的编写软件。如果你设置了适当的测试用例,可以消除大多数功能性的错误,并且更好地维护你的软件。

整合 PHPunit 到 phalcon(Integrating PHPunit with phalcon)

如果你还没有安装好 phpunit,可以使用以下 composer 命令:

composer require phpunit/phpunit

或者手动添加 composer.json:

{
    "require-dev": {
        "phpunit/phpunit": "~4.5"
    }
}

phpunit 安装后将会在你的根目录创建一个名为 ‘tests’ 的目录:

app/
public/
tests/

接下来,我们需要用一个 ‘helper’ 文件来引导单元测试程序。

PHPunit 辅助文件(The PHPunit helper file)

需要使用 helper 文件来引导运行测试程序。我们预先准备好一个示例文件,将该文件放到 tests/ 目录下并命名为 TestHelper.php

<?php

use Phalcon\Di;
use Phalcon\Di\FactoryDefault;
use Phalcon\Loader;

ini_set("display_errors", 1);
error_reporting(E_ALL);

define("ROOT_PATH", __DIR__);

set_include_path(
    ROOT_PATH . PATH_SEPARATOR . get_include_path()
);

// Required for phalcon/incubator
include __DIR__ . "/../vendor/autoload.php";

// Use the application autoloader to autoload the classes
// Autoload the dependencies found in composer
$loader = new Loader();

$loader->registerDirs(
    [
        ROOT_PATH,
    ]
);

$loader->register();

$di = new FactoryDefault();

Di::reset();

// Add any needed services to the DI here

Di::setDefault($di);

你需要从自己的 library 类库中测试组件,将它们添加到 autoloader 加载器或在主程序中使用 autoloader 加载器。

为了更好地帮助你构建单元测试,我们写了一些抽象的类库,你可以使用这些抽象类来引导单元测试。 这些文件在 @ https://github.com/phalcon/incubator.

你可以添加 incubator 依赖库:

composer require phalcon/incubator

或手动添加到 composer.json:

{
    "require": {
        "phalcon/incubator": "dev-master"
    }
}

你也可以使用链接克隆仓库。

PHPunit.xml 文件(PHPunit.xml file)

现在,创建一个 phpunit 文件:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./TestHelper.php"
         backupGlobals="false"
         backupStaticAttributes="false"
         verbose="true"
         colors="false"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="true">
    <testsuite name="Phalcon - Testsuite">
        <directory>./</directory>
    </testsuite>
</phpunit>

按照你的需求修改 phpunit.xml 然后保存到 tests/ 目录。

你将在 tests/ 目录运行所有测试。

简单的单元测试(Sample unit test)

要运行任何单元测试,你要事先定义好。autoloader 加载器将确保正确的文件被加载进来,所以你需要做的是创建文件然后 phpunit 运行测试。

该示例不包含配置文件,但大多数测试用例都需要配置文件,你可以将它添加到 DI 得到 UnitTestCase 文件。

首先在 /tests 目录创建一个 UnitTestCase.php 基本单元测试:

<?php

use Phalcon\Di;
use Phalcon\Test\UnitTestCase as PhalconTestCase;

abstract class UnitTestCase extends PhalconTestCase
{
    /**
     * @var bool
     */
    private $_loaded = false;



    public function setUp()
    {
        parent::setUp();

        // Load any additional services that might be required during testing
        $di = Di::getDefault();

        // Get any DI components here. If you have a config, be sure to pass it to the parent

        $this->setDi($di);

        $this->_loaded = true;
    }

    /**
     * Check if the test case is setup properly
     *
     * @throws \PHPUnit_Framework_IncompleteTestError;
     */
    public function __destruct()
    {
        if (!$this->_loaded) {
            throw new \PHPUnit_Framework_IncompleteTestError(
                "Please run parent::setUp()."
            );
        }
    }
}

独立命名空间的单元测试是一个很好的主意,对于这个测试创建命名空间 ‘Test’,即创建一个文件名为 testsTestUnitTest.php:

<?php

namespace Test;

/**
 * Class UnitTest
 */
class UnitTest extends \UnitTestCase
{
    public function testTestCase()
    {
        $this->assertEquals(
            "works",
            "works",
            "This is OK"
        );

        $this->assertEquals(
            "works",
            "works1",
            "This will fail"
        );
    }
}

你现在可以在命令行 tests 目录执行 ‘phpunit’ 得到以下输出:

$ phpunit
PHPUnit 3.7.23 by Sebastian Bergmann.

Configuration read from /private/var/www/tests/phpunit.xml

Time: 3 ms, Memory: 3.25Mb

There was 1 failure:

1) Test\UnitTest::testTestCase
This will fail
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'works'
+'works1'

/private/var/www/tests/Test/UnitTest.php:25

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.

现在,你可以开始构建单元测试了。你可以在这里查看一份很好的指南(如果你不熟悉PHPUnit,我们也推荐阅读PHPUnit文档)

http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/

进阶技巧 / 延伸阅读

提高性能:下一步该做什么?(Increasing Performance: What’s next?)

要开发出高性能的应用程序需要考虑多方面的因素: 服务器, 客户端, 网络, 数据库, web服务器,静态资源等。 本章中我集中分析在如何提升系统的性能及 如何检测应用的瓶颈。

关于服务端(Profile on the Server)

每种应用都有不同, 持久的性能分析对找出系统瓶颈是非常必要的。 性能分析可以让我们更直观的看出何处为性能瓶颈,何处不是。 性能分析在一个请示中和另一请求中可能表现 不一,所以要做出足够的分析及权衡方可给出结论。

关于 XDebug(Profiling with XDebug)

Xdebug 提供了简易的性能测试的方式, 安装后可在php.ini中 进行如下配置:

xdebug.profiler_enable = On

使用 Webgrind 可以分析出哪些函数或方法比其它的要慢:

_images/webgrind.jpg
关于 Xhprof(Profiling with Xhprof)

Xhprof 也是一个非常有意思的扩展。 开发者可以添加如下的代码到启动文件中:

<?php

xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

然后在启动文件的结尾保存性能分析数据:

<?php

$xhprof_data = xhprof_disable('/tmp');

$XHPROF_ROOT = "/var/www/xhprof/";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_testing");

echo "http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";

Xhprof 提供了一个内置的HTML视图用来对性能分析的数据进行展示:

_images/xhprof-2.jpg
_images/xhprof-1.jpg
关于 SQL 语句(Profiling SQL Statements)

几乎所有的数据库系统都提供了相关的工具以找出哪些执行缓慢的SQL语句。 检测及修复那些执行缓慢的查询对提高服务器端系统的性能来说是非常重要的。 在Mysql数据库中, 开发者可以启用慢查询日志来记录执行缓慢的查询:

log-slow-queries = /var/log/slow-queries.log
long_query_time = 1.5
关于客户端(Profile on the Client)

有时开发者需要提升静态资源加载的速度, 比如图片, javascript, CSS等。 下面的工具可以让开发者从客户端检测静态资源加载的瓶颈:

(使用Chrome/Firefox进行性能分析)Profile with Chrome/Firefox

几乎所有的现代浏览器都有相应的工具来检测页面加载时间。 Chrome中开发者可使用web探察器来获取一个页面的所有资源加载所需的时间:

_images/chrome-1.jpg

Firebug 提供了类似的功能:

_images/firefox-1.jpg
Yahoo! YSlow

开发者可以使用 YSlow 对网页进行分析, YSlow给出基于 rules for high performance web pages (高性能网页规)的建议:

_images/yslow-1.jpg
使用Speed Trace进行性能分析(Profile with Speed Tracer)

Speed Tracer 这个工具可以帮助开发者找出web应用性能方面的问题。 这个工个从浏览器的底层分析出web应用的性能。 Speed Tracer 这个插可以安装 在Windows或Linux版本的Chrome上。

_images/speed-tracer.jpg

这是一个非常有用的工具,它可以为我们显示出html页面渲染的时间, Javascript及css执行(渲染)的时间等。

使用最新的 PHP 版本(Use a recent PHP version)

PHP本身的执行速度已经越来越快了, 使用最新版本的PHP及Phalcon可以更高的提升web应用的执行速度。

使用 PHP 字节码缓存(Use a PHP Bytecode Cache)

APC 像其它的字节码缓存工具一样可以帮助web应用程序减少读取及解析php文件解析所花的时间。 安装完APC之后在php.ini中添加如何配置:

apc.enabled = On

PHP5.5中包含了一个内置的字节码缓存器,即 ZendOptimizer+, 这个扩展在5.3及5.4版本的php中也存在,只不过不是内置的而是用扩展的形式存在的。

将可能发生阻塞的操作放到后台运行(Do blocking work in the background)

处理视频, 发送e-mail, 压缩文件和图片等是非常耗时的, 这些最好放在后台执行。 开发者可以使用队列及消息系统以提高web应用的性能,可使用如下组件:

Google Page Speed

mod_pagespeed 可以加速网站的运行速度及减少网站的加载时间。 这个开源的apache web服务器模块(nginx下为 ngx_pagespeed )会 自动对网页,静态资源(CSS, JavaScript, images)等进行性能相关的优化,而无需开发者修改已存在的代码,内容,及工作流等。

注: 更多的性能相关的配置或建议可以查看具体的web服务器, 如apache中提供了mod_cache, mod_disk_cache等.

Dependency Injection Explained

接下来的例子有些长,但解释了为什么我们使用依赖注入与服务定位器. 首先,假设我们正在开发一个组件,叫SomeComponent,它执行的内容现在还不重要。 我们的组件需要依赖数据库的连接。

在下面第一个例子中,数据库的连接是在组件内部建立的。这种方法是不实用的;事实上这样做的话,我们不能改变创建数据库连接的参数或者选择不同的数据库系统,因为连接是当组件被创建时建立的。

<?php

class SomeComponent
{
    /**
     * 连接数据库的实例是被写死在组件的内部
     * 因此,我们很难从外部替换或者改变它的行为
     */
    public function someDbTask()
    {
        $connection = new Connection(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );

        // ...
    }
}

$some = new SomeComponent();

$some->someDbTask();

为了解决这样的情况,我们建立一个setter,在使用前注入独立外部依赖。现在,看起来似乎是一个不错的解决办法:

<?php

class SomeComponent
{
    protected $_connection;

    /**
     * 设置外部传入的数据库的连接实例
     */
    public function setConnection($connection)
    {
        $this->_connection = $connection;
    }

    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }
}

$some = new SomeComponent();

// 建立数据库连接实例
$connection = new Connection(
    [
        "host"     => "localhost",
        "username" => "root",
        "password" => "secret",
        "dbname"   => "invo",
    ]
);

// 向组件注入数据连接实例
$some->setConnection($connection);

$some->someDbTask();

想一下,假设我们使用这个组件在应用内的好几个地方都用到,然而我们在注入连接实例时还需要建立好几次数据的连接实例。 如果我们可以获取到数据库的连接实例而不用每次都要创建新的连接实例,使用某种全局注册表可以解决这样的问题:

<?php

class Registry
{
    /**
     * 返回数据库连接实例
     */
    public static function getConnection()
    {
        return new Connection(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );
    }
}

class SomeComponent
{
    protected $_connection;

    /**
     * 设置外部传入的数据库的连接实例
     */
    public function setConnection($connection)
    {
        $this->_connection = $connection;
    }

    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }
}

$some = new SomeComponent();

// 把注册表中的连接实例传递给组件
$some->setConnection(Registry::getConnection());

$some->someDbTask();

现在,让我们设想一下,我们必须实现2个方法,第一个方法是总是创建一个新的连接,第二方法是总是使用一个共享连接:

<?php

class Registry
{
    protected static $_connection;

    /**
     * 建立一个新的连接实例
     */
    protected static function _createConnection()
    {
        return new Connection(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );
    }

    /**
     * 只建立一个连接实例,后面的请求只返回该连接实例
     */
    public static function getSharedConnection()
    {
        if (self::$_connection === null) {
            self::$_connection = self::_createConnection();
        }

        return self::$_connection;
    }

    /**
     * 总是返回一个新的连接实例
     */
    public static function getNewConnection()
    {
        return self::_createConnection();
    }
}

class SomeComponent
{
    protected $_connection;

    /**
     * 设置外部传入的数据库的连接实例
     */
    public function setConnection($connection)
    {
        $this->_connection = $connection;
    }

    /**
     * 这个方法总是需要共享连接实例
     */
    public function someDbTask()
    {
        $connection = $this->_connection;

        // ...
    }

    /**
     * 这个方法总是需要新的连接实例
     */
    public function someOtherDbTask($connection)
    {

    }
}

$some = new SomeComponent();

// 注入共享连接实例
$some->setConnection(
    Registry::getSharedConnection()
);

$some->someDbTask();

// 这里我们总是传递一个新的连接实例
$some->someOtherDbTask(
    Registry::getNewConnection()
);

到目前为止,我们已经看到依赖注入怎么解决我们的问题了。把依赖作为参数来传递,而不是建立在内部建立它们,这使我们的应用更加容易维护和更加解耦。不管怎么样,长期来说,这种形式的依赖注入有一些缺点。

例如,如果这个组件有很多依赖, 我们需要创建多个参数的setter方法​​来传递依赖关系,或者建立一个多个参数的构造函数来传递它们,另外在使用组件前还要每次都创建依赖,这让我们的代码像这样不易维护:

<?php

// 创建依赖实例或从注册表中查找
$connection = new Connection();
$session    = new Session();
$fileSystem = new FileSystem();
$filter     = new Filter();
$selector   = new Selector();

// 把实例作为参数传递给构造函数
$some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);

// ... 或者使用setter
$some->setConnection($connection);
$some->setSession($session);
$some->setFileSystem($fileSystem);
$some->setFilter($filter);
$some->setSelector($selector);

假设我们必须在应用的不同地方使用和创建这些对象。如果当你永远不需要任何依赖实例时,你需要去删掉构造函数的参数,或者去删掉注入的setter。为了解决这样的问题,我们再次回到全局注册表创建组件。不管怎么样,在创建对象之前,它增加了一个新的抽象层:

<?php

class SomeComponent
{
    // ...

    /**
     * Define a factory method to create SomeComponent instances injecting its dependencies
     */
    public static function factory()
    {
        $connection = new Connection();
        $session    = new Session();
        $fileSystem = new FileSystem();
        $filter     = new Filter();
        $selector   = new Selector();

        return new self($connection, $session, $fileSystem, $filter, $selector);
    }
}

瞬间,我们又回到刚刚开始的问题了,我们再次创建依赖实例在组件内部!我们可以继续前进,找出一个每次能奏效的方法去解决这个问题。但似乎一次又一次,我们又回到了不实用的例子中。

一个实用和优雅的解决方法,是为依赖实例提供一个容器。这个容器担任全局的注册表,就像我们刚才看到的那样。使用依赖实例的容器作为一个桥梁来获取依赖实例,使我们能够降低我们的组件的复杂性:

<?php

use Phalcon\Di;
use Phalcon\DiInterface;

class SomeComponent
{
    protected $_di;

    public function __construct(DiInterface $di)
    {
        $this->_di = $di;
    }

    public function someDbTask()
    {
        // 获得数据库连接实例
        // 总是返回一个新的连接
        $connection = $this->_di->get("db");
    }

    public function someOtherDbTask()
    {
        // 获得共享连接实例
        // 每次请求都返回相同的连接实例
        $connection = $this->_di->getShared("db");

        // 这个方法也需要一个输入过滤的依赖服务
        $filter = $this->_di->get("filter");
    }
}

$di = new Di();

// 在容器中注册一个db服务
$di->set(
    "db",
    function () {
        return new Connection(
            [
                "host"     => "localhost",
                "username" => "root",
                "password" => "secret",
                "dbname"   => "invo",
            ]
        );
    }
);

// 在容器中注册一个filter服务
$di->set(
    "filter",
    function () {
        return new Filter();
    }
);

// 在容器中注册一个session服务
$di->set(
    "session",
    function () {
        return new Session();
    }
);

// 把传递服务的容器作为唯一参数传递给组件
$some = new SomeComponent($di);

$some->someDbTask();

这个组件现在可以很简单的获取到它所需要的服务,服务采用延迟加载的方式,只有在需要使用的时候才初始化,这也节省了服务器资源。这个组件现在是高度解耦。例如,我们可以替换掉创建连接的方式,它们的行为或它们的任何其他方面,也不会影响该组件。

Understanding How Phalcon Applications Work

如果你已经看过了 tutorial 或者已经通过 Phalcon Devtools 生成了代码, 你将很容易识别以下的启动文件:

<?php

use Phalcon\Mvc\Application;

// 注册自动加载器
// ...

// 注册服务
// ...

// 处理请求
$application = new Application($di);

try {
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo "Exception: ", $e->getMessage();
}

控制器中全部核心的工作都会在handle()被回调时触发执行。

<?php

$response = $application->handle();
手动启动(Manual bootstrapping)

如果你不想使用 Phalcon\Mvc\Application ,以上的代码可以改成这样:

<?php

// 获取 'router' 服务
$router = $di["router"];

$router->handle();

$view = $di["view"];

$dispatcher = $di["dispatcher"];

// 传递路由的相关数据传递给调度器

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

// 启动视图
$view->start();

// 请求调度
$dispatcher->dispatch();

// 渲染相关视图
$view->render(
    $dispatcher->getControllerName(),
    $dispatcher->getActionName(),
    $dispatcher->getParams()
);

// 完成视图
$view->finish();

$response = $di["response"];

// 传递视图内容给响应对象
$response->setContent(
    $view->getContent()
);

// Send the response
$response->send();

以下代码替换了 Phalcon\Mvc\Application ,虽然缺少了视图组件, 但却更适合Rest风格的API接口:

<?php

use Phalcon\Http\ResponseInterface;

// 获取 'router' 服务
$router = $di["router"];

$router->handle();

$dispatcher = $di["dispatcher"];

// 传递路由的相关数据传递给调度器

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

// 请求调度
$dispatcher->dispatch();

// 获取最后的返回结果
$response = $dispatcher->getReturnedValue();

// 判断结果是否是 'response' 对象
if ($response instanceof ResponseInterface) {
    // 发送响应
    $response->send();
}

另外一个修改就是在分发器中对抛出异常的捕捉可以将请求转发到其他的操作:

<?php

use Phalcon\Http\ResponseInterface;

// 获取 'router' 服务
$router = $di["router"];

$router->handle();

$dispatcher = $di["dispatcher"];

// 传递路由的相关数据传递给调度器

$dispatcher->setControllerName(
    $router->getControllerName()
);

$dispatcher->setActionName(
    $router->getActionName()
);

$dispatcher->setParams(
    $router->getParams()
);

try {
    // 请求调度
    $dispatcher->dispatch();
} catch (Exception $e) {
    // An exception has occurred, dispatch some controller/action aimed for that

    // Pass the processed router parameters to the dispatcher
    $dispatcher->setControllerName("errors");
    $dispatcher->setActionName("action503");

    // Dispatch the request
    $dispatcher->dispatch();
}

// 获取最后的返回结果
$response = $dispatcher->getReturnedValue();

// 判断结果是否是 'response' 对象
if ($response instanceof ResponseInterface) {
    // 发送响应
    $response->send();
}

尽管上面的代码比使用 Phalcon\Mvc\Application 而需要的代码远远要累赘得很, 但它为启动你的应用提供了一个可修改、可定制化的途径。 因为根据你的项目需要,你可以想对实例什么和不实例化什么进行完全的控制,或者想用你自己的组件来替代那些确定和必须的组件从而扩展默认的功能。

API

API Indice

Abstract class Phalcon\Acl

Source on GitHub

Constants

integer ALLOW

integer DENY

Abstract class Phalcon\Acl\Adapter

implements Phalcon\Acl\AdapterInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

Adapter for Phalcon\Acl adapters

Methods

public getActiveRole ()

Role which the list is checking if it’s allowed to certain resource/access

public getActiveResource ()

Resource which the list is checking if some role can access it

public getActiveAccess ()

Active access which the list is checking if some role can access it

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public getEventsManager ()

Returns the internal event manager

public setDefaultAction (mixed $defaultAccess)

Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY)

public getDefaultAction ()

Returns the default ACL access level

abstract public setNoArgumentsDefaultAction (mixed $defaultAccess) inherited from Phalcon\Acl\AdapterInterface

...

abstract public getNoArgumentsDefaultAction () inherited from Phalcon\Acl\AdapterInterface

...

abstract public addRole (mixed $role, [mixed $accessInherits]) inherited from Phalcon\Acl\AdapterInterface

...

abstract public addInherit (mixed $roleName, mixed $roleToInherit) inherited from Phalcon\Acl\AdapterInterface

...

abstract public isRole (mixed $roleName) inherited from Phalcon\Acl\AdapterInterface

...

abstract public isResource (mixed $resourceName) inherited from Phalcon\Acl\AdapterInterface

...

abstract public addResource (mixed $resourceObject, mixed $accessList) inherited from Phalcon\Acl\AdapterInterface

...

abstract public addResourceAccess (mixed $resourceName, mixed $accessList) inherited from Phalcon\Acl\AdapterInterface

...

abstract public dropResourceAccess (mixed $resourceName, mixed $accessList) inherited from Phalcon\Acl\AdapterInterface

...

abstract public allow (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func]) inherited from Phalcon\Acl\AdapterInterface

...

abstract public deny (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func]) inherited from Phalcon\Acl\AdapterInterface

...

abstract public isAllowed (mixed $roleName, mixed $resourceName, mixed $access, [array $parameters]) inherited from Phalcon\Acl\AdapterInterface

...

abstract public getRoles () inherited from Phalcon\Acl\AdapterInterface

...

abstract public getResources () inherited from Phalcon\Acl\AdapterInterface

...

Class Phalcon\Acl\Adapter\Memory

extends abstract class Phalcon\Acl\Adapter

implements Phalcon\Events\EventsAwareInterface, Phalcon\Acl\AdapterInterface

Source on GitHub

Manages ACL lists in memory

<?php

$acl = new \Phalcon\Acl\Adapter\Memory();

$acl->setDefaultAction(Phalcon\Acl::DENY);

//Register roles
$roles = array(
    'users' => new \Phalcon\Acl\Role('Users'),
    'guests' => new \Phalcon\Acl\Role('Guests')
);
foreach ($roles as $role) {
    $acl->addRole($role);
}

//Private area resources
$privateResources = array(
    'companies' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'products' => array('index', 'search', 'new', 'edit', 'save', 'create', 'delete'),
    'invoices' => array('index', 'profile')
);
foreach ($privateResources as $resource => $actions) {
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

//Public area resources
$publicResources = array(
    'index' => array('index'),
    'about' => array('index'),
    'session' => array('index', 'register', 'start', 'end'),
    'contact' => array('index', 'send')
);
foreach ($publicResources as $resource => $actions) {
    $acl->addResource(new Phalcon\Acl\Resource($resource), $actions);
}

//Grant access to public areas to both users and guests
foreach ($roles as $role){
    foreach ($publicResources as $resource => $actions) {
            $acl->allow($role->getName(), $resource, '*');
    }
}

//Grant access to private area to role Users
foreach ($privateResources as $resource => $actions) {
            foreach ($actions as $action) {
            $acl->allow('Users', $resource, $action);
    }
}
Methods

public __construct ()

Phalcon\Acl\Adapter\Memory constructor

public addRole (RoleInterface | string $role, [array | string $accessInherits])

Adds a role to the ACL list. Second parameter allows inheriting access data from other existing role Example:

<?php

    $acl->addRole(new Phalcon\Acl\Role('administrator'), 'consultant');
    $acl->addRole('administrator', 'consultant');

public addInherit (mixed $roleName, mixed $roleToInherit)

Do a role inherit from another existing role

public isRole (mixed $roleName)

Check whether role exist in the roles list

public isResource (mixed $resourceName)

Check whether resource exist in the resources list

public addResource (Phalcon\Acl\Resource | string $resourceValue, array | string $accessList)

Adds a resource to the ACL list Access names can be a particular action, by example search, update, delete, etc or a list of them Example:

<?php

 //Add a resource to the the list allowing access to an action
 $acl->addResource(new Phalcon\Acl\Resource('customers'), 'search');
 $acl->addResource('customers', 'search');

 //Add a resource  with an access list
 $acl->addResource(new Phalcon\Acl\Resource('customers'), array('create', 'search'));
 $acl->addResource('customers', array('create', 'search'));

public addResourceAccess (mixed $resourceName, array | string $accessList)

Adds access to resources

public dropResourceAccess (mixed $resourceName, array | string $accessList)

Removes an access from a resource

protected _allowOrDeny (mixed $roleName, mixed $resourceName, mixed $access, mixed $action, [mixed $func])

Checks if a role has access to a resource

public allow (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func])

Allow access to a role on a resource You can use ‘*’ as wildcard Example:

<?php

 //Allow access to guests to search on customers
 $acl->allow('guests', 'customers', 'search');

 //Allow access to guests to search or create on customers
 $acl->allow('guests', 'customers', array('search', 'create'));

 //Allow access to any role to browse on products
 $acl->allow('*', 'products', 'browse');

 //Allow access to any role to browse on any resource
 $acl->allow('*', '*', 'browse');

public deny (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func])

Deny access to a role on a resource You can use ‘*’ as wildcard Example:

<?php

 //Deny access to guests to search on customers
 $acl->deny('guests', 'customers', 'search');

 //Deny access to guests to search or create on customers
 $acl->deny('guests', 'customers', array('search', 'create'));

 //Deny access to any role to browse on products
 $acl->deny('*', 'products', 'browse');

 //Deny access to any role to browse on any resource
 $acl->deny('*', '*', 'browse');

public isAllowed (mixed $roleName, mixed $resourceName, mixed $access, [array $parameters])

Check whether a role is allowed to access an action from a resource

<?php

 //Does andres have access to the customers resource to create?
 $acl->isAllowed('andres', 'Products', 'create');

 //Do guests have access to any resource to edit?
 $acl->isAllowed('guests', '*', 'edit');

public setNoArgumentsDefaultAction (mixed $defaultAccess)

Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY) for no arguments provided in isAllowed action if there exists func for accessKey

public getNoArgumentsDefaultAction ()

Returns the default ACL access level for no arguments provided in isAllowed action if there exists func for accessKey

public getRoles ()

Return an array with every role registered in the list

public getResources ()

Return an array with every resource registered in the list

public getActiveRole () inherited from Phalcon\Acl\Adapter

Role which the list is checking if it’s allowed to certain resource/access

public getActiveResource () inherited from Phalcon\Acl\Adapter

Resource which the list is checking if some role can access it

public getActiveAccess () inherited from Phalcon\Acl\Adapter

Active access which the list is checking if some role can access it

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Acl\Adapter

Sets the events manager

public getEventsManager () inherited from Phalcon\Acl\Adapter

Returns the internal event manager

public setDefaultAction (mixed $defaultAccess) inherited from Phalcon\Acl\Adapter

Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY)

public getDefaultAction () inherited from Phalcon\Acl\Adapter

Returns the default ACL access level

Class Phalcon\Acl\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Acl\Resource

implements Phalcon\Acl\ResourceInterface

Source on GitHub

This class defines resource entity and its description

Methods

public getName ()

Resource name

public __toString ()

Resource name

public getDescription ()

Resource description

public __construct (mixed $name, [mixed $description])

Phalcon\Acl\Resource constructor

Class Phalcon\Acl\Role

implements Phalcon\Acl\RoleInterface

Source on GitHub

This class defines role entity and its description

Methods

public getName ()

Role name

public __toString ()

Role name

public getDescription ()

Role description

public __construct (mixed $name, [mixed $description])

Phalcon\Acl\Role constructor

Abstract class Phalcon\Annotations\Adapter

implements Phalcon\Annotations\AdapterInterface

Source on GitHub

This is the base class for Phalcon\Annotations adapters

Methods

public setReader (Phalcon\Annotations\ReaderInterface $reader)

Sets the annotations parser

public getReader ()

Returns the annotation reader

public get (string | object $className)

Parses or retrieves all the annotations found in a class

public getMethods (mixed $className)

Returns the annotations found in all the class’ methods

public getMethod (mixed $className, mixed $methodName)

Returns the annotations found in a specific method

public getProperties (mixed $className)

Returns the annotations found in all the class’ methods

public getProperty (mixed $className, mixed $propertyName)

Returns the annotations found in a specific property

Class Phalcon\Annotations\Adapter\Apc

extends abstract class Phalcon\Annotations\Adapter

implements Phalcon\Annotations\AdapterInterface

Source on GitHub

Stores the parsed annotations in APC. This adapter is suitable for production

<?php

 $annotations = new \Phalcon\Annotations\Adapter\Apc();
Methods

public __construct ([array $options])

Phalcon\Annotations\Adapter\Apc constructor

public Phalcon\Annotations\Reflection read (string $key)

Reads parsed annotations from APC

public write (mixed $key, Phalcon\Annotations\Reflection $data)

Writes parsed annotations to APC

public setReader (Phalcon\Annotations\ReaderInterface $reader) inherited from Phalcon\Annotations\Adapter

Sets the annotations parser

public getReader () inherited from Phalcon\Annotations\Adapter

Returns the annotation reader

public get (string | object $className) inherited from Phalcon\Annotations\Adapter

Parses or retrieves all the annotations found in a class

public getMethods (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getMethod (mixed $className, mixed $methodName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific method

public getProperties (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getProperty (mixed $className, mixed $propertyName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific property

Class Phalcon\Annotations\Adapter\Files

extends abstract class Phalcon\Annotations\Adapter

implements Phalcon\Annotations\AdapterInterface

Source on GitHub

Stores the parsed annotations in files. This adapter is suitable for production

<?php

 use Phalcon\Annotations\Adapter\Files;

 $annotations = new Files(['annotationsDir' => 'app/cache/annotations/']);
Methods

public __construct ([array $options])

Phalcon\Annotations\Adapter\Files constructor

public Phalcon\Annotations\Reflection read (string $key)

Reads parsed annotations from files

public write (mixed $key, Phalcon\Annotations\Reflection $data)

Writes parsed annotations to files

public setReader (Phalcon\Annotations\ReaderInterface $reader) inherited from Phalcon\Annotations\Adapter

Sets the annotations parser

public getReader () inherited from Phalcon\Annotations\Adapter

Returns the annotation reader

public get (string | object $className) inherited from Phalcon\Annotations\Adapter

Parses or retrieves all the annotations found in a class

public getMethods (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getMethod (mixed $className, mixed $methodName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific method

public getProperties (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getProperty (mixed $className, mixed $propertyName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific property

Class Phalcon\Annotations\Adapter\Memory

extends abstract class Phalcon\Annotations\Adapter

implements Phalcon\Annotations\AdapterInterface

Source on GitHub

Stores the parsed annotations in memory. This adapter is the suitable development/testing

Methods

public Phalcon\Annotations\Reflection read (string $key)

Reads parsed annotations from memory

public write (mixed $key, Phalcon\Annotations\Reflection $data)

Writes parsed annotations to memory

public setReader (Phalcon\Annotations\ReaderInterface $reader) inherited from Phalcon\Annotations\Adapter

Sets the annotations parser

public getReader () inherited from Phalcon\Annotations\Adapter

Returns the annotation reader

public get (string | object $className) inherited from Phalcon\Annotations\Adapter

Parses or retrieves all the annotations found in a class

public getMethods (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getMethod (mixed $className, mixed $methodName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific method

public getProperties (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getProperty (mixed $className, mixed $propertyName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific property

Class Phalcon\Annotations\Adapter\Xcache

extends abstract class Phalcon\Annotations\Adapter

implements Phalcon\Annotations\AdapterInterface

Source on GitHub

Stores the parsed annotations to XCache. This adapter is suitable for production

<?php

 $annotations = new \Phalcon\Annotations\Adapter\Xcache();
Methods

public Phalcon\Annotations\Reflection read (string $key)

Reads parsed annotations from XCache

public write (mixed $key, Phalcon\Annotations\Reflection $data)

Writes parsed annotations to XCache

public setReader (Phalcon\Annotations\ReaderInterface $reader) inherited from Phalcon\Annotations\Adapter

Sets the annotations parser

public getReader () inherited from Phalcon\Annotations\Adapter

Returns the annotation reader

public get (string | object $className) inherited from Phalcon\Annotations\Adapter

Parses or retrieves all the annotations found in a class

public getMethods (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getMethod (mixed $className, mixed $methodName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific method

public getProperties (mixed $className) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in all the class’ methods

public getProperty (mixed $className, mixed $propertyName) inherited from Phalcon\Annotations\Adapter

Returns the annotations found in a specific property

Class Phalcon\Annotations\Annotation

Source on GitHub

Represents a single annotation in an annotations collection

Methods

public __construct (array $reflectionData)

Phalcon\Annotations\Annotation constructor

public getName ()

Returns the annotation’s name

public mixed getExpression (array $expr)

Resolves an annotation expression

public array getExprArguments ()

Returns the expression arguments without resolving

public array getArguments ()

Returns the expression arguments

public numberArguments ()

Returns the number of arguments that the annotation has

public mixed getArgument (int | string $position)

Returns an argument in a specific position

public boolean hasArgument (int | string $position)

Returns an argument in a specific position

public mixed getNamedArgument (mixed $name)

Returns a named argument

public mixed getNamedParameter (mixed $name)

Returns a named parameter

Class Phalcon\Annotations\Collection

implements Iterator, Traversable, Countable

Source on GitHub

Represents a collection of annotations. This class allows to traverse a group of annotations easily

<?php

 //Traverse annotations
 foreach ($classAnnotations as $annotation) {
     echo 'Name=', $annotation->getName(), PHP_EOL;
 }

 //Check if the annotations has a specific
 var_dump($classAnnotations->has('Cacheable'));

 //Get an specific annotation in the collection
 $annotation = $classAnnotations->get('Cacheable');
Methods

public __construct ([array $reflectionData])

Phalcon\Annotations\Collection constructor

public count ()

Returns the number of annotations in the collection

public rewind ()

Rewinds the internal iterator

public Phalcon\Annotations\Annotation current ()

Returns the current annotation in the iterator

public key ()

Returns the current position/key in the iterator

public next ()

Moves the internal iteration pointer to the next position

public valid ()

Check if the current annotation in the iterator is valid

public getAnnotations ()

Returns the internal annotations as an array

public get (mixed $name)

Returns the first annotation that match a name

public getAll (mixed $name)

Returns all the annotations that match a name

public has (mixed $name)

Check if an annotation exists in a collection

Class Phalcon\Annotations\Exception

extends class Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Annotations\Reader

implements Phalcon\Annotations\ReaderInterface

Source on GitHub

Parses docblocks returning an array with the found annotations

Methods

public parse (mixed $className)

Reads annotations from the class dockblocks, its methods and/or properties

public static parseDocBlock (mixed $docBlock, [mixed $file], [mixed $line])

Parses a raw doc block returning the annotations found

Class Phalcon\Annotations\Reflection

Source on GitHub

Allows to manipulate the annotations reflection in an OO manner

<?php

 use Phalcon\Annotations\Reader;
 use Phalcon\Annotations\Reflection;

 // Parse the annotations in a class
 $reader = new Reader();
 $parsing = reader->parse('MyComponent');

 // Create the reflection
 $reflection = new Reflection($parsing);

 // Get the annotations in the class docblock
 $classAnnotations = reflection->getClassAnnotations();
Methods

public __construct ([array $reflectionData])

Phalcon\Annotations\Reflection constructor

public getClassAnnotations ()

Returns the annotations found in the class docblock

public getMethodsAnnotations ()

Returns the annotations found in the methods’ docblocks

public getPropertiesAnnotations ()

Returns the annotations found in the properties’ docblocks

public array getReflectionData ()

Returns the raw parsing intermediate definitions used to construct the reflection

public static array data __set_state (mixed $data)

Restores the state of a Phalcon\Annotations\Reflection variable export

Abstract class Phalcon\Application

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Base class for Phalcon\Cli\Console and Phalcon\Mvc\Application.

Methods

public __construct ([Phalcon\DiInterface $dependencyInjector])

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public getEventsManager ()

Returns the internal event manager

public registerModules (array $modules, [mixed $merge])

Register an array of modules present in the application

<?php

 $this->registerModules(
    [
            'frontend' => [
                    'className' => 'Multiple\Frontend\Module',
                    'path'      => '../apps/frontend/Module.php'
            ],
            'backend' => [
                    'className' => 'Multiple\Backend\Module',
                    'path'      => '../apps/backend/Module.php'
            ]
    ]
 );

public getModules ()

Return the modules registered in the application

public getModule (mixed $name)

Gets the module definition registered in the application via module name

public setDefaultModule (mixed $defaultModule)

Sets the module name to be used if the router doesn’t return a valid module

public getDefaultModule ()

Returns the default module name

abstract public handle ()

Handles a request

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Application\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Assets\Collection

implements Countable, Iterator, Traversable

Source on GitHub

Represents a collection of resources

Methods

public getPrefix ()

...

public getLocal ()

...

public getResources ()

...

public getCodes ()

...

public getPosition ()

...

public getFilters ()

...

public getAttributes ()

...

public getJoin ()

...

public getTargetUri ()

...

public getTargetPath ()

...

public getTargetLocal ()

...

public getSourcePath ()

...

public add (Phalcon\Assets\Resource $resource)

Adds a resource to the collection

public addInline (Phalcon\Assets\Inline $code)

Adds an inline code to the collection

public addCss (mixed $path, [mixed $local], [mixed $filter], [mixed $attributes])

Adds a CSS resource to the collection

public addInlineCss (mixed $content, [mixed $filter], [mixed $attributes])

Adds an inline CSS to the collection

public Phalcon\Assets\Collection addJs (string $path, [boolean $local], [boolean $filter], [array $attributes])

Adds a javascript resource to the collection

public addInlineJs (mixed $content, [mixed $filter], [mixed $attributes])

Adds an inline javascript to the collection

public count ()

Returns the number of elements in the form

public rewind ()

Rewinds the internal iterator

public current ()

Returns the current resource in the iterator

public int key ()

Returns the current position/key in the iterator

public next ()

Moves the internal iteration pointer to the next position

public valid ()

Check if the current element in the iterator is valid

public setTargetPath (mixed $targetPath)

Sets the target path of the file for the filtered/join output

public setSourcePath (mixed $sourcePath)

Sets a base source path for all the resources in this collection

public setTargetUri (mixed $targetUri)

Sets a target uri for the generated HTML

public setPrefix (mixed $prefix)

Sets a common prefix for all the resources

public setLocal (mixed $local)

Sets if the collection uses local resources by default

public setAttributes (array $attributes)

Sets extra HTML attributes

public setFilters (array $filters)

Sets an array of filters in the collection

public setTargetLocal (mixed $targetLocal)

Sets the target local

public join (mixed $join)

Sets if all filtered resources in the collection must be joined in a single result file

public getRealTargetPath (mixed $basePath)

Returns the complete location where the joined/filtered collection must be written

public addFilter (Phalcon\Assets\FilterInterface $filter)

Adds a filter to the collection

Class Phalcon\Assets\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Assets\Filters\Cssmin

implements Phalcon\Assets\FilterInterface

Source on GitHub

Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property

Methods

public filter (mixed $content)

Filters the content using CSSMIN

Class Phalcon\Assets\Filters\Jsmin

implements Phalcon\Assets\FilterInterface

Source on GitHub

Deletes the characters which are insignificant to JavaScript. Comments will be removed. Tabs will be replaced with spaces. Carriage returns will be replaced with linefeeds. Most spaces and linefeeds will be removed.

Methods

public filter (mixed $content)

Filters the content using JSMIN

Class Phalcon\Assets\Filters\None

implements Phalcon\Assets\FilterInterface

Source on GitHub

Returns the content without make any modification to the original source

Methods

public filter (mixed $content)

Returns the content without be touched

Class Phalcon\Assets\Inline

Source on GitHub

Represents an inline asset

<?php

 $inline = new \Phalcon\Assets\Inline('js', 'alert("hello world");');
Methods

public getType ()

...

public getContent ()

...

public getFilter ()

...

public getAttributes ()

...

public __construct (string $type, string $content, [boolean $filter], [array $attributes])

Phalcon\Assets\Inline constructor

public setType (mixed $type)

Sets the inline’s type

public setFilter (mixed $filter)

Sets if the resource must be filtered or not

public setAttributes (array $attributes)

Sets extra HTML attributes

Class Phalcon\Assets\Inline\Css

extends class Phalcon\Assets\Inline

Source on GitHub

Represents an inlined CSS

Methods

public __construct (string $content, [boolean $filter], [array $attributes])

public getType () inherited from Phalcon\Assets\Inline

...

public getContent () inherited from Phalcon\Assets\Inline

...

public getFilter () inherited from Phalcon\Assets\Inline

...

public getAttributes () inherited from Phalcon\Assets\Inline

...

public setType (mixed $type) inherited from Phalcon\Assets\Inline

Sets the inline’s type

public setFilter (mixed $filter) inherited from Phalcon\Assets\Inline

Sets if the resource must be filtered or not

public setAttributes (array $attributes) inherited from Phalcon\Assets\Inline

Sets extra HTML attributes

Class Phalcon\Assets\Inline\Js

extends class Phalcon\Assets\Inline

Source on GitHub

Represents an inline Javascript

Methods

public __construct (string $content, [boolean $filter], [array $attributes])

public getType () inherited from Phalcon\Assets\Inline

...

public getContent () inherited from Phalcon\Assets\Inline

...

public getFilter () inherited from Phalcon\Assets\Inline

...

public getAttributes () inherited from Phalcon\Assets\Inline

...

public setType (mixed $type) inherited from Phalcon\Assets\Inline

Sets the inline’s type

public setFilter (mixed $filter) inherited from Phalcon\Assets\Inline

Sets if the resource must be filtered or not

public setAttributes (array $attributes) inherited from Phalcon\Assets\Inline

Sets extra HTML attributes

Class Phalcon\Assets\Manager

Source on GitHub

Manages collections of CSS/Javascript assets

Methods

public __construct ([array $options])

public setOptions (array $options)

Sets the manager options

public getOptions ()

Returns the manager options

public useImplicitOutput (mixed $implicitOutput)

Sets if the HTML generated must be directly printed or returned

public addCss (mixed $path, [mixed $local], [mixed $filter], [mixed $attributes])

Adds a Css resource to the ‘css’ collection

<?php

$assets->addCss('css/bootstrap.css');
$assets->addCss('http://bootstrap.my-cdn.com/style.css', false);

public addInlineCss (mixed $content, [mixed $filter], [mixed $attributes])

Adds an inline Css to the ‘css’ collection

public addJs (mixed $path, [mixed $local], [mixed $filter], [mixed $attributes])

Adds a javascript resource to the ‘js’ collection

<?php

$assets->addJs('scripts/jquery.js');
$assets->addJs('http://jquery.my-cdn.com/jquery.js', false);

public addInlineJs (mixed $content, [mixed $filter], [mixed $attributes])

Adds an inline javascript to the ‘js’ collection

public addResourceByType (mixed $type, Phalcon\Assets\Resource $resource)

Adds a resource by its type

<?php

$assets->addResourceByType('css', new \Phalcon\Assets\Resource\Css('css/style.css'));

public addInlineCodeByType (mixed $type, Phalcon\Assets\Inline $code)

Adds an inline code by its type

public addResource (Phalcon\Assets\Resource $resource)

Adds a raw resource to the manager

<?php

 $assets->addResource(new Phalcon\Assets\Resource('css', 'css/style.css'));

public addInlineCode (Phalcon\Assets\Inline $code)

Adds a raw inline code to the manager

public set (mixed $id, Phalcon\Assets\Collection $collection)

Sets a collection in the Assets Manager

<?php

 $assets->set('js', $collection);

public get (mixed $id)

Returns a collection by its id

<?php

 $scripts = $assets->get('js');

public getCss ()

Returns the CSS collection of assets

public getJs ()

Returns the CSS collection of assets

public collection (mixed $name)

Creates/Returns a collection of resources

public output (Phalcon\Assets\Collection $collection, callback $callback, string $type)

Traverses a collection calling the callback to generate its HTML

public outputInline (Phalcon\Assets\Collection $collection, string $type)

Traverses a collection and generate its HTML

public outputCss ([string $collectionName])

Prints the HTML for CSS resources

public outputInlineCss ([string $collectionName])

Prints the HTML for inline CSS

public outputJs ([string $collectionName])

Prints the HTML for JS resources

public outputInlineJs ([string $collectionName])

Prints the HTML for inline JS

public getCollections ()

Returns existing collections in the manager

public exists (mixed $id)

Returns true or false if collection exists

Class Phalcon\Assets\Resource

Source on GitHub

Represents an asset resource

<?php

 $resource = new \Phalcon\Assets\Resource('js', 'javascripts/jquery.js');
Methods

public getType ()

public getPath ()

public getLocal ()

public getFilter ()

public getAttributes ()

public getSourcePath ()

...

public getTargetPath ()

...

public getTargetUri ()

...

public __construct (string $type, string $path, [boolean $local], [boolean $filter], [array $attributes])

Phalcon\Assets\Resource constructor

public setType (mixed $type)

Sets the resource’s type

public setPath (mixed $path)

Sets the resource’s path

public setLocal (mixed $local)

Sets if the resource is local or external

public setFilter (mixed $filter)

Sets if the resource must be filtered or not

public setAttributes (array $attributes)

Sets extra HTML attributes

public setTargetUri (mixed $targetUri)

Sets a target uri for the generated HTML

public setSourcePath (mixed $sourcePath)

Sets the resource’s source path

public setTargetPath (mixed $targetPath)

Sets the resource’s target path

public getContent ([mixed $basePath])

Returns the content of the resource as an string Optionally a base path where the resource is located can be set

public getRealTargetUri ()

Returns the real target uri for the generated HTML

public getRealSourcePath ([mixed $basePath])

Returns the complete location where the resource is located

public getRealTargetPath ([mixed $basePath])

Returns the complete location where the resource must be written

Class Phalcon\Assets\Resource\Css

extends class Phalcon\Assets\Resource

Source on GitHub

Represents CSS resources

Methods

public __construct (string $path, [boolean $local], [boolean $filter], [array $attributes])

public getType () inherited from Phalcon\Assets\Resource

public getPath () inherited from Phalcon\Assets\Resource

public getLocal () inherited from Phalcon\Assets\Resource

public getFilter () inherited from Phalcon\Assets\Resource

public getAttributes () inherited from Phalcon\Assets\Resource

public getSourcePath () inherited from Phalcon\Assets\Resource

...

public getTargetPath () inherited from Phalcon\Assets\Resource

...

public getTargetUri () inherited from Phalcon\Assets\Resource

...

public setType (mixed $type) inherited from Phalcon\Assets\Resource

Sets the resource’s type

public setPath (mixed $path) inherited from Phalcon\Assets\Resource

Sets the resource’s path

public setLocal (mixed $local) inherited from Phalcon\Assets\Resource

Sets if the resource is local or external

public setFilter (mixed $filter) inherited from Phalcon\Assets\Resource

Sets if the resource must be filtered or not

public setAttributes (array $attributes) inherited from Phalcon\Assets\Resource

Sets extra HTML attributes

public setTargetUri (mixed $targetUri) inherited from Phalcon\Assets\Resource

Sets a target uri for the generated HTML

public setSourcePath (mixed $sourcePath) inherited from Phalcon\Assets\Resource

Sets the resource’s source path

public setTargetPath (mixed $targetPath) inherited from Phalcon\Assets\Resource

Sets the resource’s target path

public getContent ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the content of the resource as an string Optionally a base path where the resource is located can be set

public getRealTargetUri () inherited from Phalcon\Assets\Resource

Returns the real target uri for the generated HTML

public getRealSourcePath ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the complete location where the resource is located

public getRealTargetPath ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the complete location where the resource must be written

Class Phalcon\Assets\Resource\Js

extends class Phalcon\Assets\Resource

Source on GitHub

Represents Javascript resources

Methods

public __construct (string $path, [boolean $local], [boolean $filter], [array $attributes])

public getType () inherited from Phalcon\Assets\Resource

public getPath () inherited from Phalcon\Assets\Resource

public getLocal () inherited from Phalcon\Assets\Resource

public getFilter () inherited from Phalcon\Assets\Resource

public getAttributes () inherited from Phalcon\Assets\Resource

public getSourcePath () inherited from Phalcon\Assets\Resource

...

public getTargetPath () inherited from Phalcon\Assets\Resource

...

public getTargetUri () inherited from Phalcon\Assets\Resource

...

public setType (mixed $type) inherited from Phalcon\Assets\Resource

Sets the resource’s type

public setPath (mixed $path) inherited from Phalcon\Assets\Resource

Sets the resource’s path

public setLocal (mixed $local) inherited from Phalcon\Assets\Resource

Sets if the resource is local or external

public setFilter (mixed $filter) inherited from Phalcon\Assets\Resource

Sets if the resource must be filtered or not

public setAttributes (array $attributes) inherited from Phalcon\Assets\Resource

Sets extra HTML attributes

public setTargetUri (mixed $targetUri) inherited from Phalcon\Assets\Resource

Sets a target uri for the generated HTML

public setSourcePath (mixed $sourcePath) inherited from Phalcon\Assets\Resource

Sets the resource’s source path

public setTargetPath (mixed $targetPath) inherited from Phalcon\Assets\Resource

Sets the resource’s target path

public getContent ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the content of the resource as an string Optionally a base path where the resource is located can be set

public getRealTargetUri () inherited from Phalcon\Assets\Resource

Returns the real target uri for the generated HTML

public getRealSourcePath ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the complete location where the resource is located

public getRealTargetPath ([mixed $basePath]) inherited from Phalcon\Assets\Resource

Returns the complete location where the resource must be written

Abstract class Phalcon\Cache\Backend

Source on GitHub

This class implements common functionality for backend adapters. A backend cache adapter may extend this class

Methods

public getFrontend ()

...

public setFrontend (mixed $frontend)

...

public getOptions ()

...

public setOptions (mixed $options)

...

public getLastKey ()

...

public setLastKey (mixed $lastKey)

...

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend constructor

public mixed start (int | string $keyName, [int $lifetime])

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer])

Stops the frontend without store any cached content

public isFresh ()

Checks whether the last cache is fresh or cached

public isStarted ()

Checks whether the cache has starting buffering or not

public int getLifetime ()

Gets the last lifetime set

Class Phalcon\Cache\Backend\Apc

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data and raw data using an APC backend

<?php

 use Phalcon\Cache\Backend\Apc;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data for 2 days
 $frontCache = new FrontData([
     'lifetime' => 172800
 ]);

 $cache = new Apc($frontCache, [
     'prefix' => 'app-data'
 ]);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([string | long $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the APC backend and stops the frontend

public mixed increment ([string $keyName], [long $value])

Increment of a given key, by number $value

public mixed decrement ([string $keyName], [long $value])

Decrement of a given key, by number $value

public delete (mixed $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string | long $keyName], [long $lifetime])

Checks if cache exists and it hasn’t expired

public flush ()

Immediately invalidates all existing items.

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options]) inherited from Phalcon\Cache\Backend

Phalcon\Cache\Backend constructor

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\File

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments using a file backend

<?php

 use Phalcon\Cache\Backend\File;
 use Phalcon\Cache\Frontend\Output as FrontOutput;

 // Cache the file for 2 days
 $frontendOptions = [
     'lifetime' => 172800
 ];

 // Create an output cache
 $frontCache = FrontOutput($frontOptions);

 // Set the cache directory
 $backendOptions = [
     'cacheDir' => '../app/cache/'
 ];

 // Create the File backend
 $cache = new File($frontCache, $backendOptions);

 $content = $cache->start('my-cache');
 if ($content === null) {
     echo '<h1>', time(), '</h1>';
     $cache->save();
 } else {
     echo $content;
 }
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, array $options)

Phalcon\Cache\Backend\File constructor

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [int $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public boolean delete (int | string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string | int $prefix])

Query the existing cached keys

public boolean exists ([string | int $keyName], [int $lifetime])

Checks if cache exists and it isn’t expired

public mixed increment ([string | int $keyName], [int $value])

Increment of a given key, by number $value

public mixed decrement ([string | int $keyName], [int $value])

Decrement of a given key, by number $value

public flush ()

Immediately invalidates all existing items.

public getKey (mixed $key)

Return a file-system safe identifier for a given key

public useSafeKey (mixed $useSafeKey)

Set whether to use the safekey or not

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Libmemcached

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data or raw data to a libmemcached backend. Per default persistent memcached connection pools are used.

<?php

 use Phalcon\Cache\Backend\Libmemcached;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data for 2 days
 $frontCache = new FrontData([
     'lifetime' => 172800
 ]);

 // Create the Cache setting memcached connection options
 $cache = new Libmemcached($frontCache, [
     'servers' => [
         [
             'host' => 'localhost',
             'port' => 11211,
             'weight' => 1
         ],
     ],
     'client' => [
         \Memcached::OPT_HASH => Memcached::HASH_MD5,
         \Memcached::OPT_PREFIX_KEY => 'prefix.',
     ]
 ]);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend\Memcache constructor

public _connect ()

Create internal connection to memcached

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public boolean delete (int | string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string $keyName], [long $lifetime])

Checks if cache exists and it isn’t expired

public long increment ([string $keyName], [mixed $value])

Increment of given $keyName by $value

public long decrement ([string $keyName], [long $value])

Decrement of $keyName by given $value

public flush ()

Immediately invalidates all existing items. Memcached does not support flush() per default. If you require flush() support, set $config[“statsKey”]. All modified keys are stored in “statsKey”. Note: statsKey has a negative performance impact.

<?php

 $cache = new \Phalcon\Cache\Backend\Libmemcached($frontCache, ["statsKey" => "_PHCM"]);
 $cache->save('my-data', array(1, 2, 3, 4, 5));

 //'my-data' and all other used keys are deleted
 $cache->flush();

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Memcache

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data or raw data to a memcache backend This adapter uses the special memcached key “_PHCM” to store all the keys internally used by the adapter

<?php

 use Phalcon\Cache\Backend\Memcache;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data for 2 days
 $frontCache = new FrontData([
     'lifetime' => 172800
 ]);

 // Create the Cache setting memcached connection options
 $cache = new Memcache($frontCache, [
     'host' => 'localhost',
     'port' => 11211,
     'persistent' => false
 ]);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend\Memcache constructor

public _connect ()

Create internal connection to memcached

public addServers (mixed $host, mixed $port, [mixed $persistent])

Add servers to memcache pool

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public boolean delete (int | string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string $keyName], [long $lifetime])

Checks if cache exists and it isn’t expired

public long increment ([string $keyName], [long $value])

Increment of given $keyName by $value

public long decrement ([string $keyName], [long $value])

Decrement of $keyName by given $value

public flush ()

Immediately invalidates all existing items.

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Memory

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface, Serializable

Source on GitHub

Stores content in memory. Data is lost when the request is finished

<?php

 use Phalcon\Cache\Backend\Memory;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data
 $frontCache = new FrontData();

 $cache = new Memory($frontCache);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the backend and stops the frontend

public boolean delete (string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string | int $prefix])

Query the existing cached keys

public boolean exists ([string | int $keyName], [long $lifetime])

Checks if cache exists and it hasn’t expired

public long increment ([string $keyName], [mixed $value])

Increment of given $keyName by $value

public long decrement ([string $keyName], [long $value])

Decrement of $keyName by given $value

public flush ()

Immediately invalidates all existing items.

public serialize ()

Required for interface \Serializable

public unserialize (mixed $data)

Required for interface \Serializable

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options]) inherited from Phalcon\Cache\Backend

Phalcon\Cache\Backend constructor

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Mongo

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data or raw data to a MongoDb backend

<?php

 use Phalcon\Cache\Backend\Mongo;
 use Phalcon\Cache\Frontend\Base64;

 // Cache data for 2 days
 $frontCache = new Base64([
     'lifetime' => 172800
 ]);

 // Create a MongoDB cache
 $cache = new Mongo($frontCache, [
     'server' => "mongodb://localhost",
     'db' => 'caches',
     'collection' => 'images'
 ]);

 // Cache arbitrary data
 $cache->save('my-data', file_get_contents('some-image.jpg'));

 // Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend\Mongo constructor

final protected MongoCollection _getCollection ()

Returns a MongoDb collection based on the backend parameters

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public boolean delete (int | string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string $keyName], [long $lifetime])

Checks if cache exists and it isn’t expired

public collection->remove(...) gc ()

gc

public mixed increment (int | string $keyName, [long $value])

Increment of a given key by $value

public mixed decrement (int | string $keyName, [long $value])

Decrement of a given key by $value

public flush ()

Immediately invalidates all existing items.

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Redis

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data or raw data to a redis backend This adapter uses the special redis key “_PHCR” to store all the keys internally used by the adapter

<?php

 use Phalcon\Cache\Backend\Redis;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data for 2 days
 $frontCache = new FrontData([
     'lifetime' => 172800
 ]);

 // Create the Cache setting redis connection options
 $cache = new Redis($frontCache, [
     'host' => 'localhost',
     'port' => 6379,
     'auth' => 'foobared',
     'persistent' => false
     'index' => 0,
 ]);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend\Redis constructor

public _connect ()

Create internal connection to redis

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public delete (int | string $keyName)

Deletes a value from the cache by its key

public queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string $keyName], [long $lifetime])

Checks if cache exists and it isn’t expired

public increment ([string $keyName], [long $value])

Increment of given $keyName by $value

public decrement ([string $keyName], [long $value])

Decrement of $keyName by given $value

public flush ()

Immediately invalidates all existing items.

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Backend\Xcache

extends abstract class Phalcon\Cache\Backend

implements Phalcon\Cache\BackendInterface

Source on GitHub

Allows to cache output fragments, PHP data and raw data using an XCache backend

<?php

 use Phalcon\Cache\Backend\Xcache;
 use Phalcon\Cache\Frontend\Data as FrontData;

 // Cache data for 2 days
 $frontCache = new FrontData([
     'lifetime' => 172800
 ]);

 $cache = new Xcache($frontCache, [
     'prefix' => 'app-data'
 ]);

 // Cache arbitrary data
 $cache->save('my-data', [1, 2, 3, 4, 5]);

 // Get data
 $data = $cache->get('my-data');
Methods

public __construct (Phalcon\Cache\FrontendInterface $frontend, [array $options])

Phalcon\Cache\Backend\Xcache constructor

public get (mixed $keyName, [mixed $lifetime])

Returns a cached content

public save ([int | string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into the file backend and stops the frontend

public boolean delete (int | string $keyName)

Deletes a value from the cache by its key

public array queryKeys ([string $prefix])

Query the existing cached keys

public boolean exists ([string $keyName], [long $lifetime])

Checks if cache exists and it isn’t expired

public mixed increment (string $keyName, [long $value])

Atomic increment of a given key, by number $value

public mixed decrement (string $keyName, [long $value])

Atomic decrement of a given key, by number $value

public flush ()

Immediately invalidates all existing items.

public getFrontend () inherited from Phalcon\Cache\Backend

...

public setFrontend (mixed $frontend) inherited from Phalcon\Cache\Backend

...

public getOptions () inherited from Phalcon\Cache\Backend

...

public setOptions (mixed $options) inherited from Phalcon\Cache\Backend

...

public getLastKey () inherited from Phalcon\Cache\Backend

...

public setLastKey (mixed $lastKey) inherited from Phalcon\Cache\Backend

...

public mixed start (int | string $keyName, [int $lifetime]) inherited from Phalcon\Cache\Backend

Starts a cache. The keyname allows to identify the created fragment

public stop ([mixed $stopBuffer]) inherited from Phalcon\Cache\Backend

Stops the frontend without store any cached content

public isFresh () inherited from Phalcon\Cache\Backend

Checks whether the last cache is fresh or cached

public isStarted () inherited from Phalcon\Cache\Backend

Checks whether the cache has starting buffering or not

public int getLifetime () inherited from Phalcon\Cache\Backend

Gets the last lifetime set

Class Phalcon\Cache\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Cache\Frontend\Base64

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache data converting/deconverting them to base64. This adapter uses the base64_encode/base64_decode PHP’s functions

<?php

<?php

 // Cache the files for 2 days using a Base64 frontend
 $frontCache = new \Phalcon\Cache\Frontend\Base64(array(
    "lifetime" => 172800
 ));

 //Create a MongoDB cache
 $cache = new \Phalcon\Cache\Backend\Mongo($frontCache, array(
    'server' => "mongodb://localhost",
      'db' => 'caches',
    'collection' => 'images'
 ));

 // Try to get cached image
 $cacheKey = 'some-image.jpg.cache';
 $image    = $cache->get($cacheKey);
 if ($image === null) {

     // Store the image in the cache
     $cache->save($cacheKey, file_get_contents('tmp-dir/some-image.jpg'));
 }

 header('Content-Type: image/jpeg');
 echo $image;
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Base64 constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing in this adapter

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public string beforeStore (mixed $data)

Serializes data before storing them

public mixed afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Frontend\Data

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache native PHP data in a serialized form

<?php

  use Phalcon\Cache\Backend\File;
  use Phalcon\Cache\Frontend\Data;

  // Cache the files for 2 days using a Data frontend
  $frontCache = new Data(['lifetime' => 172800]);

  // Create the component that will cache "Data" to a 'File' backend
  // Set the cache file directory - important to keep the '/' at the end of
  // of the value for the folder
  $cache = new File($frontCache, ['cacheDir' => '../app/cache/']);

  // Try to get cached records
  $cacheKey = 'robots_order_id.cache';
  $robots   = $cache->get($cacheKey);

  if ($robots === null) {
      // $robots is null due to cache expiration or data does not exist
      // Make the database call and populate the variable
      $robots = Robots::find(['order' => 'id']);

      // Store it in the cache
      $cache->save($cacheKey, $robots);
  }

  // Use $robots :)
  foreach ($robots as $robot) {
      echo $robot->name, "\n";
  }
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Data constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Serializes data before storing them

public afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Frontend\Igbinary

extends class Phalcon\Cache\Frontend\Data

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache native PHP data in a serialized form using igbinary extension

<?php

// Cache the files for 2 days using Igbinary frontend
$frontCache = new \Phalcon\Cache\Frontend\Igbinary(array(
    "lifetime" => 172800
));

// Create the component that will cache "Igbinary" to a "File" backend
// Set the cache file directory - important to keep the "/" at the end of
// of the value for the folder
$cache = new \Phalcon\Cache\Backend\File($frontCache, array(
    "cacheDir" => "../app/cache/"
));

// Try to get cached records
$cacheKey  = 'robots_order_id.cache';
$robots    = $cache->get($cacheKey);
if ($robots === null) {

    // $robots is null due to cache expiration or data do not exist
    // Make the database call and populate the variable
    $robots = Robots::find(array("order" => "id"));

    // Store it in the cache
    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Data constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public string beforeStore (mixed $data)

Serializes data before storing them

public mixed afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Frontend\Json

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache data converting/deconverting them to JSON. This adapter uses the json_encode/json_decode PHP’s functions As the data is encoded in JSON other systems accessing the same backend could process them

<?php

<?php

 // Cache the data for 2 days
 $frontCache = new \Phalcon\Cache\Frontend\Json(array(
    "lifetime" => 172800
 ));

 //Create the Cache setting memcached connection options
 $cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array(
    'host' => 'localhost',
    'port' => 11211,
    'persistent' => false
 ));

 //Cache arbitrary data
 $cache->save('my-data', array(1, 2, 3, 4, 5));

 //Get data
 $data = $cache->get('my-data');
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Base64 constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public string beforeStore (mixed $data)

Serializes data before storing them

public mixed afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Frontend\Msgpack

extends class Phalcon\Cache\Frontend\Data

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache native PHP data in a serialized form using msgpack extension This adapter uses a Msgpack frontend to store the cached content and requires msgpack extension.

<?php

 use Phalcon\Cache\Backend\File;
 use Phalcon\Cache\Frontend\Msgpack;

 // Cache the files for 2 days using Msgpack frontend
 $frontCache = new Msgpack([
     'lifetime' => 172800
 ]);

 // Create the component that will cache "Msgpack" to a "File" backend
 // Set the cache file directory - important to keep the "/" at the end of
 // of the value for the folder
 $cache = new File($frontCache, [
     'cacheDir' => '../app/cache/'
 ]);

 // Try to get cached records
 $cacheKey = 'robots_order_id.cache';
 $robots   = $cache->get($cacheKey);
 if ($robots === null) {
     // $robots is null due to cache expiration or data do not exist
     // Make the database call and populate the variable
     $robots = Robots::find(['order' => 'id']);

     // Store it in the cache
     $cache->save($cacheKey, $robots);
 }

 // Use $robots
 foreach ($robots as $robot) {
     echo $robot->name, "\n";
 }
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Msgpack constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Actually, does nothing

public getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Serializes data before storing them

public afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Frontend\None

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Discards any kind of frontend data input. This frontend does not have expiration time or any other options

<?php

<?php

//Create a None Cache
$frontCache = new \Phalcon\Cache\Frontend\None();

// Create the component that will cache "Data" to a "Memcached" backend
// Memcached connection settings
$cache = new \Phalcon\Cache\Backend\Memcache($frontCache, array(
    "host" => "localhost",
    "port" => "11211"
));

// This Frontend always return the data as it's returned by the backend
$cacheKey = 'robots_order_id.cache';
$robots    = $cache->get($cacheKey);
if ($robots === null) {

    // This cache doesn't perform any expiration checking, so the data is always expired
    // Make the database call and populate the variable
    $robots = Robots::find(array("order" => "id"));

    $cache->save($cacheKey, $robots);
}

// Use $robots :)
foreach ($robots as $robot) {
    echo $robot->name, "\n";
}
Methods

public getLifetime ()

Returns cache lifetime, always one second expiring content

public isBuffering ()

Check whether if frontend is buffering output, always false

public start ()

Starts output frontend

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public beforeStore (mixed $data)

Prepare data to be stored

public afterRetrieve (mixed $data)

Prepares data to be retrieved to user

Class Phalcon\Cache\Frontend\Output

implements Phalcon\Cache\FrontendInterface

Source on GitHub

Allows to cache output fragments captured with ob_* functions

<?php

*
* use Phalcon\Tag;
* use Phalcon\Cache\Backend\File;
* use Phalcon\Cache\Frontend\Output;
*
* // Create an Output frontend. Cache the files for 2 days
* $frontCache = new Output(['lifetime' => 172800]));
*
* // Create the component that will cache from the "Output" to a "File" backend
* // Set the cache file directory - it's important to keep the "/" at the end of
* // the value for the folder
* $cache = new File($frontCache, ['cacheDir' => '../app/cache/']);
*
* // Get/Set the cache file to ../app/cache/my-cache.html
* $content = $cache->start('my-cache.html');
*
* // If $content is null then the content will be generated for the cache
* if (null === $content) {
*     // Print date and time
*     echo date('r');
*
*     // Generate a link to the sign-up action
*     echo Tag::linkTo(
*         [
*             'user/signup',
*             'Sign Up',
*             'class' => 'signup-button'
*         ]
*     );
*
*     // Store the output into the cache file
*     $cache->save();
* } else {
*     // Echo the cached output
*     echo $content;
* }
Methods

public __construct ([array $frontendOptions])

Phalcon\Cache\Frontend\Output constructor

public getLifetime ()

Returns the cache lifetime

public isBuffering ()

Check whether if frontend is buffering output

public start ()

Starts output frontend. Currently, does nothing

public string getContent ()

Returns output cached content

public stop ()

Stops output frontend

public string beforeStore (mixed $data)

Serializes data before storing them

public mixed afterRetrieve (mixed $data)

Unserializes data after retrieval

Class Phalcon\Cache\Multiple

Source on GitHub

Allows to read to chained backend adapters writing to multiple backends

<?php

   use Phalcon\Cache\Frontend\Data as DataFrontend,
       Phalcon\Cache\Multiple,
       Phalcon\Cache\Backend\Apc as ApcCache,
       Phalcon\Cache\Backend\Memcache as MemcacheCache,
       Phalcon\Cache\Backend\File as FileCache;

   $ultraFastFrontend = new DataFrontend(array(
       "lifetime" => 3600
   ));

   $fastFrontend = new DataFrontend(array(
       "lifetime" => 86400
   ));

   $slowFrontend = new DataFrontend(array(
       "lifetime" => 604800
   ));

   //Backends are registered from the fastest to the slower
   $cache = new Multiple(array(
       new ApcCache($ultraFastFrontend, array(
           "prefix" => 'cache',
       )),
       new MemcacheCache($fastFrontend, array(
           "prefix" => 'cache',
           "host" => "localhost",
           "port" => "11211"
       )),
       new FileCache($slowFrontend, array(
           "prefix" => 'cache',
           "cacheDir" => "../app/cache/"
       ))
   ));

   //Save, saves in every backend
   $cache->save('my-key', $data);
Methods

public __construct ([Phalcon\Cache\BackendInterface[] $backends])

Phalcon\Cache\Multiple constructor

public push (Phalcon\Cache\BackendInterface $backend)

Adds a backend

public mixed get (string | int $keyName, [long $lifetime])

Returns a cached content reading the internal backends

public start (string | int $keyName, [long $lifetime])

Starts every backend

public save ([string $keyName], [string $content], [long $lifetime], [boolean $stopBuffer])

Stores cached content into all backends and stops the frontend

public boolean delete (string | int $keyName)

Deletes a value from each backend

public boolean exists ([string | int $keyName], [long $lifetime])

Checks if cache exists in at least one backend

public flush ()

Flush all backend(s)

Class Phalcon\Cli\Console

extends abstract class Phalcon\Application

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This component allows to create CLI applications using Phalcon

Methods

public addModules (array $modules)

Merge modules with the existing ones

<?php

application->addModules(array(
    'admin' => array(
            'className' => 'Multiple\Admin\Module',
            'path' => '../apps/admin/Module.php'
    )
));

public handle ([array $arguments])

Handle the whole command-line tasks

public setArgument ([array $arguments], [mixed $str], [mixed $shift])

Set an specific argument

public __construct ([Phalcon\DiInterface $dependencyInjector]) inherited from Phalcon\Application

Phalcon\Application

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Application

Sets the events manager

public getEventsManager () inherited from Phalcon\Application

Returns the internal event manager

public registerModules (array $modules, [mixed $merge]) inherited from Phalcon\Application

Register an array of modules present in the application

<?php

 $this->registerModules(
    [
            'frontend' => [
                    'className' => 'Multiple\Frontend\Module',
                    'path'      => '../apps/frontend/Module.php'
            ],
            'backend' => [
                    'className' => 'Multiple\Backend\Module',
                    'path'      => '../apps/backend/Module.php'
            ]
    ]
 );

public getModules () inherited from Phalcon\Application

Return the modules registered in the application

public getModule (mixed $name) inherited from Phalcon\Application

Gets the module definition registered in the application via module name

public setDefaultModule (mixed $defaultModule) inherited from Phalcon\Application

Sets the module name to be used if the router doesn’t return a valid module

public getDefaultModule () inherited from Phalcon\Application

Returns the default module name

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Cli\Console\Exception

extends class Phalcon\Application\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Cli\Dispatcher

extends abstract class Phalcon\Dispatcher

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\DispatcherInterface, Phalcon\Cli\DispatcherInterface

Source on GitHub

Dispatching is the process of taking the command-line arguments, extracting the module name, task name, action name, and optional parameters contained in it, and then instantiating a task and calling an action on it.

<?php

$di = new \Phalcon\Di();

$dispatcher = new \Phalcon\Cli\Dispatcher();

  $dispatcher->setDi(di);

$dispatcher->setTaskName('posts');
$dispatcher->setActionName('index');
$dispatcher->setParams(array());

$handle = dispatcher->dispatch();
Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public setTaskSuffix (mixed $taskSuffix)

Sets the default task suffix

public setDefaultTask (mixed $taskName)

Sets the default task name

public setTaskName (mixed $taskName)

Sets the task name to be dispatched

public getTaskName ()

Gets last dispatched task name

protected _throwDispatchException (mixed $message, [mixed $exceptionCode])

Throws an internal exception

protected _handleException (Exception $exception)

Handles a user exception

public getLastTask ()

Returns the lastest dispatched controller

public getActiveTask ()

Returns the active task in the dispatcher

public setOptions (array $options)

Set the options to be dispatched

public getOptions ()

Get dispatched options

public callActionMethod (mixed $handler, mixed $actionMethod, [array $params])

...

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Dispatcher

Sets the dependency injector

public getDI () inherited from Phalcon\Dispatcher

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Dispatcher

Sets the events manager

public getEventsManager () inherited from Phalcon\Dispatcher

Returns the internal event manager

public setActionSuffix (mixed $actionSuffix) inherited from Phalcon\Dispatcher

Sets the default action suffix

public getActionSuffix () inherited from Phalcon\Dispatcher

Gets the default action suffix

public setModuleName (mixed $moduleName) inherited from Phalcon\Dispatcher

Sets the module where the controller is (only informative)

public getModuleName () inherited from Phalcon\Dispatcher

Gets the module where the controller class is

public setNamespaceName (mixed $namespaceName) inherited from Phalcon\Dispatcher

Sets the namespace where the controller class is

public getNamespaceName () inherited from Phalcon\Dispatcher

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (mixed $namespaceName) inherited from Phalcon\Dispatcher

Sets the default namespace

public getDefaultNamespace () inherited from Phalcon\Dispatcher

Returns the default namespace

public setDefaultAction (mixed $actionName) inherited from Phalcon\Dispatcher

Sets the default action name

public setActionName (mixed $actionName) inherited from Phalcon\Dispatcher

Sets the action name to be dispatched

public getActionName () inherited from Phalcon\Dispatcher

Gets the latest dispatched action name

public setParams (array $params) inherited from Phalcon\Dispatcher

Sets action params to be dispatched

public getParams () inherited from Phalcon\Dispatcher

Gets action params

public setParam (mixed $param, mixed $value) inherited from Phalcon\Dispatcher

Set a param by its name or numeric index

public mixed getParam (mixed $param, [string | array $filters], [mixed $defaultValue]) inherited from Phalcon\Dispatcher

Gets a param by its name or numeric index

public boolean hasParam (mixed $param) inherited from Phalcon\Dispatcher

Check if a param exists

public getActiveMethod () inherited from Phalcon\Dispatcher

Returns the current method to be/executed in the dispatcher

public isFinished () inherited from Phalcon\Dispatcher

Checks if the dispatch loop is finished or has more pendent controllers/tasks to dispatch

public setReturnedValue (mixed $value) inherited from Phalcon\Dispatcher

Sets the latest returned value by an action manually

public mixed getReturnedValue () inherited from Phalcon\Dispatcher

Returns value returned by the latest dispatched action

public setModelBinding (boolean $value) inherited from Phalcon\Dispatcher

Enable/Disable model binding during dispatch

public object dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

protected object _dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

public forward (array $forward) inherited from Phalcon\Dispatcher

Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed

<?php

  $this->dispatcher->forward(array("controller" => "posts", "action" => "index"));

public wasForwarded () inherited from Phalcon\Dispatcher

Check if the current executed action was forwarded by another one

public getHandlerClass () inherited from Phalcon\Dispatcher

Possible class name that will be located to dispatch the request

protected _resolveEmptyProperties () inherited from Phalcon\Dispatcher

Set empty properties to their defaults (where defaults are available)

Class Phalcon\Cli\Dispatcher\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Cli\Router

implements Phalcon\Di\InjectionAwareInterface

Source on GitHub

Phalcon\Cli\Router is the standard framework router. Routing is the process of taking a command-line arguments and decomposing it into parameters to determine which module, task, and action of that task should receive the request

<?php

$router = new \Phalcon\Cli\Router();
$router->handle(array(
    'module' => 'main',
    'task' => 'videos',
    'action' => 'process'
));
echo $router->getTaskName();
Methods

public __construct ([mixed $defaultRoutes])

Phalcon\Cli\Router constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setDefaultModule (mixed $moduleName)

Sets the name of the default module

public setDefaultTask (mixed $taskName)

Sets the default controller name

public setDefaultAction (mixed $actionName)

Sets the default action name

public setDefaults (array $defaults)

Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route

<?php

 $router->setDefaults(array(
    'module' => 'common',
    'action' => 'index'
 ));

public handle ([array $arguments])

Handles routing information received from command-line arguments

public Phalcon\Cli\Router\Route add (string $pattern, [string/array $paths])

Adds a route to the router

<?php

 $router->add('/about', 'About::main');

public getModuleName ()

Returns proccesed module name

public getTaskName ()

Returns proccesed task name

public getActionName ()

Returns processed action name

public array getParams ()

Returns processed extra params

public getMatchedRoute ()

Returns the route that matches the handled URI

public array getMatches ()

Returns the sub expressions in the regular expression matched

public wasMatched ()

Checks if the router matches any of the defined routes

public getRoutes ()

Returns all the routes defined in the router

public Phalcon\Cli\Router\Route getRouteById (int $id)

Returns a route object by its id

public getRouteByName (mixed $name)

Returns a route object by its name

Class Phalcon\Cli\Router\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Cli\Router\Route

Source on GitHub

This class represents every route added to the router

Constants

string DEFAULT_DELIMITER

Methods

public __construct (string $pattern, [array $paths])

Phalcon\Cli\Router\Route constructor

public compilePattern (mixed $pattern)

Replaces placeholders from pattern returning a valid PCRE regular expression

public array | boolean extractNamedParams (string $pattern)

Extracts parameters from a string

public reConfigure (string $pattern, [array $paths])

Reconfigure the route adding a new pattern and a set of paths

public getName ()

Returns the route’s name

public setName (mixed $name)

Sets the route’s name

<?php

 $router->add('/about', array(
     'controller' => 'about'
 ))->setName('about');

public Phalcon\Cli\Router\Route beforeMatch (callback $callback)

Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched

public mixed getBeforeMatch ()

Returns the ‘before match’ callback if any

public getRouteId ()

Returns the route’s id

public getPattern ()

Returns the route’s pattern

public getCompiledPattern ()

Returns the route’s compiled pattern

public getPaths ()

Returns the paths

public getReversedPaths ()

Returns the paths using positions as keys and names as values

public Phalcon\Cli\Router\Route convert (string $name, callable $converter)

Adds a converter to perform an additional transformation for certain parameter

public getConverters ()

Returns the router converter

public static reset ()

Resets the internal route id generator

public static delimiter ([mixed $delimiter])

Set the routing delimiter

public static getDelimiter ()

Get routing delimiter

Class Phalcon\Cli\Task

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Cli\TaskInterface

Source on GitHub

Every command-line task should extend this class that encapsulates all the task functionality A task can be used to run “tasks” such as migrations, cronjobs, unit-tests, or anything that you want. The Task class should at least have a “mainAction” method

<?php

class HelloTask extends \Phalcon\Cli\Task
{

  // This action will be executed by default
  public function mainAction()
  {

  }

  public function findAction()
  {

  }

}
Methods

final public __construct ()

Phalcon\Cli\Task constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Config

implements ArrayAccess, Countable

Source on GitHub

Phalcon\Config is designed to simplify the access to, and the use of, configuration data within applications. It provides a nested object property based user interface for accessing this configuration data within application code.

<?php

$config = new \Phalcon\Config(array(
    "database" => array(
            "adapter" => "Mysql",
            "host" => "localhost",
            "username" => "scott",
            "password" => "cheetah",
            "dbname" => "test_db"
    ),
    "phalcon" => array(
            "controllersDir" => "../app/controllers/",
            "modelsDir" => "../app/models/",
            "viewsDir" => "../app/views/"
    )
 ));
Methods

public __construct ([array $arrayConfig])

Phalcon\Config constructor

public offsetExists (mixed $index)

Allows to check whether an attribute is defined using the array-syntax

<?php

 var_dump(isset($config['database']));

public get (mixed $index, [mixed $defaultValue])

Gets an attribute from the configuration, if the attribute isn’t defined returns null If the value is exactly null or is not defined the default value will be used instead

<?php

 echo $config->get('controllersDir', '../app/controllers/');

public offsetGet (mixed $index)

Gets an attribute using the array-syntax

<?php

 print_r($config['database']);

public offsetSet (mixed $index, mixed $value)

Sets an attribute using the array-syntax

<?php

 $config['database'] = array('type' => 'Sqlite');

public offsetUnset (mixed $index)

Unsets an attribute using the array-syntax

<?php

 unset($config['database']);

public merge (Phalcon\Config $config)

Merges a configuration into the current one

<?php

 $appConfig = new \Phalcon\Config(array('database' => array('host' => 'localhost')));
 $globalConfig->merge($config2);

public toArray ()

Converts recursively the object to an array

<?php

print_r($config->toArray());

public count ()

Returns the count of properties set in the config

<?php

 print count($config);

or

<?php

 print $config->count();

public static __set_state (array $data)

Restores the state of a Phalcon\Config object

final protected Config merged config _merge (Config $config, [mixed $instance])

Helper method for merge configs (forwarding nested config instance)

Class Phalcon\Config\Adapter\Ini

extends class Phalcon\Config

implements Countable, ArrayAccess

Source on GitHub

Reads ini files and converts them to Phalcon\Config objects. Given the next configuration file:

  <?php

   [database]
   adapter = Mysql
   host = localhost
   username = scott
   password = cheetah
   dbname = test_db

   [phalcon]
   controllersDir = "../app/controllers/"
   modelsDir = "../app/models/"
   viewsDir = "../app/views/"

You can read it as follows:
  <?php

   $config = new Phalcon\Config\Adapter\Ini("path/config.ini");
   echo $config->phalcon->controllersDir;
   echo $config->database->username;

PHP constants may also be parsed in the ini file, so if you define a constant as an ini value before calling the constructor, the constant's value will be integrated into the results. To use it this way you must specify the optional second parameter as INI_SCANNER_NORMAL when calling the constructor:
<?php

  $config = new Phalcon\Config\Adapter\Ini("path/config-with-constants.ini", INI_SCANNER_NORMAL);
Methods

public __construct (mixed $filePath, [mixed $mode])

Phalcon\Config\Adapter\Ini constructor

protected _parseIniString (mixed $path, mixed $value)

Build multidimensional array from string

<?php

 $this->_parseIniString('path.hello.world', 'value for last key');

 // result
 [
      'path' => [
          'hello' => [
              'world' => 'value for last key',
          ],
      ],
 ];

private _cast (mixed $ini)

We have to cast values manually because parse_ini_file() has a poor implementation.

public offsetExists (mixed $index) inherited from Phalcon\Config

Allows to check whether an attribute is defined using the array-syntax

<?php

 var_dump(isset($config['database']));

public get (mixed $index, [mixed $defaultValue]) inherited from Phalcon\Config

Gets an attribute from the configuration, if the attribute isn’t defined returns null If the value is exactly null or is not defined the default value will be used instead

<?php

 echo $config->get('controllersDir', '../app/controllers/');

public offsetGet (mixed $index) inherited from Phalcon\Config

Gets an attribute using the array-syntax

<?php

 print_r($config['database']);

public offsetSet (mixed $index, mixed $value) inherited from Phalcon\Config

Sets an attribute using the array-syntax

<?php

 $config['database'] = array('type' => 'Sqlite');

public offsetUnset (mixed $index) inherited from Phalcon\Config

Unsets an attribute using the array-syntax

<?php

 unset($config['database']);

public merge (Phalcon\Config $config) inherited from Phalcon\Config

Merges a configuration into the current one

<?php

 $appConfig = new \Phalcon\Config(array('database' => array('host' => 'localhost')));
 $globalConfig->merge($config2);

public toArray () inherited from Phalcon\Config

Converts recursively the object to an array

<?php

print_r($config->toArray());

public count () inherited from Phalcon\Config

Returns the count of properties set in the config

<?php

 print count($config);

or

<?php

 print $config->count();

public static __set_state (array $data) inherited from Phalcon\Config

Restores the state of a Phalcon\Config object

final protected Config merged config _merge (Config $config, [mixed $instance]) inherited from Phalcon\Config

Helper method for merge configs (forwarding nested config instance)

Class Phalcon\Config\Adapter\Json

extends class Phalcon\Config

implements Countable, ArrayAccess

Source on GitHub

Reads JSON files and converts them to Phalcon\Config objects. Given the following configuration file:

  <?php

   {"phalcon":{"baseuri":"\/phalcon\/"},"models":{"metadata":"memory"}}

You can read it as follows:
<?php

 $config = new Phalcon\Config\Adapter\Json("path/config.json");
 echo $config->phalcon->baseuri;
 echo $config->models->metadata;
Methods

public __construct (mixed $filePath)

Phalcon\Config\Adapter\Json constructor

public offsetExists (mixed $index) inherited from Phalcon\Config

Allows to check whether an attribute is defined using the array-syntax

<?php

 var_dump(isset($config['database']));

public get (mixed $index, [mixed $defaultValue]) inherited from Phalcon\Config

Gets an attribute from the configuration, if the attribute isn’t defined returns null If the value is exactly null or is not defined the default value will be used instead

<?php

 echo $config->get('controllersDir', '../app/controllers/');

public offsetGet (mixed $index) inherited from Phalcon\Config

Gets an attribute using the array-syntax

<?php

 print_r($config['database']);

public offsetSet (mixed $index, mixed $value) inherited from Phalcon\Config

Sets an attribute using the array-syntax

<?php

 $config['database'] = array('type' => 'Sqlite');

public offsetUnset (mixed $index) inherited from Phalcon\Config

Unsets an attribute using the array-syntax

<?php

 unset($config['database']);

public merge (Phalcon\Config $config) inherited from Phalcon\Config

Merges a configuration into the current one

<?php

 $appConfig = new \Phalcon\Config(array('database' => array('host' => 'localhost')));
 $globalConfig->merge($config2);

public toArray () inherited from Phalcon\Config

Converts recursively the object to an array

<?php

print_r($config->toArray());

public count () inherited from Phalcon\Config

Returns the count of properties set in the config

<?php

 print count($config);

or

<?php

 print $config->count();

public static __set_state (array $data) inherited from Phalcon\Config

Restores the state of a Phalcon\Config object

final protected Config merged config _merge (Config $config, [mixed $instance]) inherited from Phalcon\Config

Helper method for merge configs (forwarding nested config instance)

Class Phalcon\Config\Adapter\Php

extends class Phalcon\Config

implements Countable, ArrayAccess

Source on GitHub

Reads php files and converts them to Phalcon\Config objects. Given the next configuration file:

  <?php

  <?php
  return array(
   'database' => array(
       'adapter' => 'Mysql',
       'host' => 'localhost',
       'username' => 'scott',
       'password' => 'cheetah',
       'dbname' => 'test_db'
   ),

   'phalcon' => array(
      'controllersDir' => '../app/controllers/',
      'modelsDir' => '../app/models/',
      'viewsDir' => '../app/views/'
  ));

You can read it as follows:
<?php

 $config = new Phalcon\Config\Adapter\Php("path/config.php");
 echo $config->phalcon->controllersDir;
 echo $config->database->username;
Methods

public __construct (mixed $filePath)

Phalcon\Config\Adapter\Php constructor

public offsetExists (mixed $index) inherited from Phalcon\Config

Allows to check whether an attribute is defined using the array-syntax

<?php

 var_dump(isset($config['database']));

public get (mixed $index, [mixed $defaultValue]) inherited from Phalcon\Config

Gets an attribute from the configuration, if the attribute isn’t defined returns null If the value is exactly null or is not defined the default value will be used instead

<?php

 echo $config->get('controllersDir', '../app/controllers/');

public offsetGet (mixed $index) inherited from Phalcon\Config

Gets an attribute using the array-syntax

<?php

 print_r($config['database']);

public offsetSet (mixed $index, mixed $value) inherited from Phalcon\Config

Sets an attribute using the array-syntax

<?php

 $config['database'] = array('type' => 'Sqlite');

public offsetUnset (mixed $index) inherited from Phalcon\Config

Unsets an attribute using the array-syntax

<?php

 unset($config['database']);

public merge (Phalcon\Config $config) inherited from Phalcon\Config

Merges a configuration into the current one

<?php

 $appConfig = new \Phalcon\Config(array('database' => array('host' => 'localhost')));
 $globalConfig->merge($config2);

public toArray () inherited from Phalcon\Config

Converts recursively the object to an array

<?php

print_r($config->toArray());

public count () inherited from Phalcon\Config

Returns the count of properties set in the config

<?php

 print count($config);

or

<?php

 print $config->count();

public static __set_state (array $data) inherited from Phalcon\Config

Restores the state of a Phalcon\Config object

final protected Config merged config _merge (Config $config, [mixed $instance]) inherited from Phalcon\Config

Helper method for merge configs (forwarding nested config instance)

Class Phalcon\Config\Adapter\Yaml

extends class Phalcon\Config

implements Countable, ArrayAccess

Source on GitHub

Reads YAML files and converts them to Phalcon\Config objects. Given the following configuration file:

  <?php

   phalcon:
     baseuri:        /phalcon/
     controllersDir: !approot  /app/controllers/
   models:
     metadata: memory

You can read it as follows:
<?php

 define('APPROOT', dirname(__DIR__));

 $config = new Phalcon\Config\Adapter\Yaml("path/config.yaml", [
     '!approot' => function($value) {
         return APPROOT . $value;
     }
 ]);

 echo $config->phalcon->controllersDir;
 echo $config->phalcon->baseuri;
 echo $config->models->metadata;
Methods

public __construct (mixed $filePath, [array $callbacks])

Phalcon\Config\Adapter\Yaml constructor

public offsetExists (mixed $index) inherited from Phalcon\Config

Allows to check whether an attribute is defined using the array-syntax

<?php

 var_dump(isset($config['database']));

public get (mixed $index, [mixed $defaultValue]) inherited from Phalcon\Config

Gets an attribute from the configuration, if the attribute isn’t defined returns null If the value is exactly null or is not defined the default value will be used instead

<?php

 echo $config->get('controllersDir', '../app/controllers/');

public offsetGet (mixed $index) inherited from Phalcon\Config

Gets an attribute using the array-syntax

<?php

 print_r($config['database']);

public offsetSet (mixed $index, mixed $value) inherited from Phalcon\Config

Sets an attribute using the array-syntax

<?php

 $config['database'] = array('type' => 'Sqlite');

public offsetUnset (mixed $index) inherited from Phalcon\Config

Unsets an attribute using the array-syntax

<?php

 unset($config['database']);

public merge (Phalcon\Config $config) inherited from Phalcon\Config

Merges a configuration into the current one

<?php

 $appConfig = new \Phalcon\Config(array('database' => array('host' => 'localhost')));
 $globalConfig->merge($config2);

public toArray () inherited from Phalcon\Config

Converts recursively the object to an array

<?php

print_r($config->toArray());

public count () inherited from Phalcon\Config

Returns the count of properties set in the config

<?php

 print count($config);

or

<?php

 print $config->count();

public static __set_state (array $data) inherited from Phalcon\Config

Restores the state of a Phalcon\Config object

final protected Config merged config _merge (Config $config, [mixed $instance]) inherited from Phalcon\Config

Helper method for merge configs (forwarding nested config instance)

Class Phalcon\Config\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Crypt

implements Phalcon\CryptInterface

Source on GitHub

Provides encryption facilities to phalcon applications

<?php

$crypt = new \Phalcon\Crypt();

$key = 'le password';
$text = 'This is a secret text';

$encrypted = $crypt->encrypt($text, $key);

echo $crypt->decrypt($encrypted, $key);
Constants

integer PADDING_DEFAULT

integer PADDING_ANSI_X_923

integer PADDING_PKCS7

integer PADDING_ISO_10126

integer PADDING_ISO_IEC_7816_4

integer PADDING_ZERO

integer PADDING_SPACE

Methods

public setPadding (mixed $scheme)

Changes the padding scheme used

public setCipher (mixed $cipher)

Sets the cipher algorithm

public getCipher ()

Returns the current cipher

public setKey (mixed $key)

Sets the encryption key

public getKey ()

Returns the encryption key

protected _cryptPadText (mixed $text, mixed $mode, mixed $blockSize, mixed $paddingType)

Pads texts before encryption

protected _cryptUnpadText (mixed $text, mixed $mode, mixed $blockSize, mixed $paddingType)

If the function detects that the text was not padded, it will return it unmodified

public encrypt (mixed $text, [mixed $key])

Encrypts a text

<?php

$encrypted = $crypt->encrypt("Ultra-secret text", "encrypt password");

public decrypt (mixed $text, [mixed $key])

Decrypts an encrypted text

<?php

echo $crypt->decrypt($encrypted, "decrypt password");

public encryptBase64 (mixed $text, [mixed $key], [mixed $safe])

Encrypts a text returning the result as a base64 string

public decryptBase64 (mixed $text, [mixed $key], [mixed $safe])

Decrypt a text that is coded as a base64 string

public getAvailableCiphers ()

Returns a list of available ciphers

Class Phalcon\Crypt\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Db

Source on GitHub

Phalcon\Db and its related classes provide a simple SQL database interface for Phalcon Framework. The Phalcon\Db is the basic class you use to connect your PHP application to an RDBMS. There is a different adapter class for each brand of RDBMS. This component is intended to lower level database operations. If you want to interact with databases using higher level of abstraction use Phalcon\Mvc\Model. Phalcon\Db is an abstract class. You only can use it with a database adapter like Phalcon\Db\Adapter\Pdo

<?php

use Phalcon\Db;
use Phalcon\Db\Exception;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlConnection;

try {

  $connection = new MysqlConnection(array(
     'host' => '192.168.0.11',
     'username' => 'sigma',
     'password' => 'secret',
     'dbname' => 'blog',
     'port' => '3306',
  ));

  $result = $connection->query("SELECT * FROM robots LIMIT 5");
  $result->setFetchMode(Db::FETCH_NUM);
  while ($robot = $result->fetch()) {
    print_r($robot);
  }

} catch (Exception $e) {
echo $e->getMessage(), PHP_EOL;
}
Constants

integer FETCH_LAZY

integer FETCH_ASSOC

integer FETCH_NAMED

integer FETCH_NUM

integer FETCH_BOTH

integer FETCH_OBJ

integer FETCH_BOUND

integer FETCH_COLUMN

integer FETCH_CLASS

integer FETCH_INTO

integer FETCH_FUNC

integer FETCH_GROUP

integer FETCH_UNIQUE

integer FETCH_KEY_PAIR

integer FETCH_CLASSTYPE

integer FETCH_SERIALIZE

integer FETCH_PROPS_LATE

Methods

public static setup (array $options)

Enables/disables options in the Database component

Abstract class Phalcon\Db\Adapter

implements Phalcon\Events\EventsAwareInterface

Source on GitHub

Base class for Phalcon\Db adapters

Methods

public getDialectType ()

Name of the dialect used

public getType ()

Type of database system the adapter is used for

public getSqlVariables ()

Active SQL bound parameter variables

public __construct (array $descriptor)

Phalcon\Db\Adapter constructor

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public getEventsManager ()

Returns the internal event manager

public setDialect (Phalcon\Db\DialectInterface $dialect)

Sets the dialect used to produce the SQL

public getDialect ()

Returns internal dialect instance

public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $bindParams], [mixed $bindTypes])

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fetchOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, [int $fetchMode], [array $bindParams], [array $bindTypes])

Dumps the complete result of a query into an array

<?php

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}

public string | ** fetchColumn (string $sqlQuery, [array $placeholders], [int | string $column])

Returns the n’th field of first row in a SQL query result

<?php

//Getting count of robots
$robotsCount = $connection->fetchColumn("SELECT count(*) FROM robots");
print_r($robotsCount);

//Getting name of last edited robot
$robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1);
print_r($robot);

public boolean insert (string | array $table, array $values, [array $fields], [array $dataTypes])

Inserts data into a table using custom RDBMS SQL syntax

<?php

 // Inserting a new robot
 $success = $connection->insert(
 "robots",
 array("Astro Boy", 1952),
 array("name", "year")
 );

 // Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean insertAsDict (string $table, array $data, [array $dataTypes])

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insertAsDict(
 "robots",
 array(
      "name" => "Astro Boy",
      "year" => 1952
  )
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string | array $table, array $fields, array $values, [string | array $whereCondition], [array $dataTypes])

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

 //Updating existing robot with array condition and $dataTypes
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 array(
     'conditions' => "id = ?",
     'bind' => array($some_unsafe_id),
     'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param
 ),
 array(PDO::PARAM_STR)
 );

Warning! If $whereCondition is string it not escaped.

public boolean updateAsDict (string $table, array $data, [string $whereCondition], [array $dataTypes])

Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax

<?php

 //Updating existing robot
 $success = $connection->updateAsDict(
 "robots",
 array(
      "name" => "New Astro Boy"
  ),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string | array $table, [string $whereCondition], [array $placeholders], [array $dataTypes])

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
 "robots",
 "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList)

Gets a list of columns

public limit (mixed $sqlQuery, mixed $number)

Appends a LIMIT clause to $sqlQuery argument

<?php

    echo $connection->limit("SELECT * FROM robots", 5);

public tableExists (mixed $tableName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.table

<?php

    var_dump($connection->tableExists("blog", "posts"));

public viewExists (mixed $viewName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.view

<?php

 var_dump($connection->viewExists("active_users", "posts"));

public forUpdate (mixed $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

public sharedLock (mixed $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

public createTable (mixed $tableName, mixed $schemaName, array $definition)

Creates a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists])

Drops a table from a schema/database

public createView (mixed $viewName, array $definition, [mixed $schemaName])

Creates a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

Drops a view

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

Adds a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

Modifies a table column based on a definition

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

Drops a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Adds an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

Drop an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Adds a primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName)

Drops a table’s primary key

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

Adds a foreign key to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

Drops a foreign key from a table

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Returns the SQL column definition from a column

public listTables ([mixed $schemaName])

List all tables on a database

<?php

    print_r($connection->listTables("blog"));

public listViews ([mixed $schemaName])

List all views on a database

<?php

print_r($connection->listViews("blog"));

public Phalcon\Db\Index[] describeIndexes (string $table, [string $schema])

Lists table indexes

<?php

print_r($connection->describeIndexes('robots_parts'));

public describeReferences (mixed $table, [mixed $schema])

Lists table references

<?php

 print_r($connection->describeReferences('robots_parts'));

public tableOptions (mixed $tableName, [mixed $schemaName])

Gets creation options from a table

<?php

 print_r($connection->tableOptions('robots'));

public createSavepoint (mixed $name)

Creates a new savepoint

public releaseSavepoint (mixed $name)

Releases given savepoint

public rollbackSavepoint (mixed $name)

Rollbacks given savepoint

public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints)

Set if nested transactions should use savepoints

public isNestedTransactionsWithSavepoints ()

Returns if nested transactions should use savepoints

public getNestedTransactionSavepointName ()

Returns the savepoint name to use for nested transactions

public getDefaultIdValue ()

Returns the default identity value to be inserted in an identity column

<?php

 //Inserting a new robot with a valid default value for the column 'id'
 $success = $connection->insert(
 "robots",
 array($connection->getDefaultIdValue(), "Astro Boy", 1952),
 array("id", "name", "year")
 );

public getDefaultValue ()

Returns the default value to make the RBDM use the default value declared in the table definition

<?php

 //Inserting a new robot with a valid default value for the column 'year'
 $success = $connection->insert(
 "robots",
 array("Astro Boy", $connection->getDefaultValue()),
 array("name", "year")
 );

public supportSequences ()

Check whether the database system requires a sequence to produce auto-numeric values

public useExplicitIdValue ()

Check whether the database system requires an explicit value for identity columns

public getDescriptor ()

Return descriptor used to connect to the active database

public string getConnectionId ()

Gets the active connection unique identifier

public getSQLStatement ()

Active SQL statement in the object

public getRealSQLStatement ()

Active SQL statement in the object without replace bound paramters

public array getSQLBindTypes ()

Active SQL statement in the object

Abstract class Phalcon\Db\Adapter\Pdo

extends abstract class Phalcon\Db\Adapter

implements Phalcon\Events\EventsAwareInterface

Source on GitHub

Phalcon\Db\Adapter\Pdo is the Phalcon\Db that internally uses PDO to connect to a database

<?php

 use Phalcon\Db\Adapter\Pdo\Mysql;

 $config = [
   'host'     => 'localhost',
   'dbname'   => 'blog',
   'port'     => 3306,
   'username' => 'sigma',
   'password' => 'secret'
 ];

 $connection = new Mysql($config);
Methods

public __construct (array $descriptor)

Constructor for Phalcon\Db\Adapter\Pdo

public connect ([array $descriptor])

This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.

<?php

 use Phalcon\Db\Adapter\Pdo\Mysql;

 // Make a connection
 $connection = new Mysql([
  'host'     => 'localhost',
  'username' => 'sigma',
  'password' => 'secret',
  'dbname'   => 'blog',
  'port'     => 3306,
 ]);

 // Reconnect
 $connection->connect();

public prepare (mixed $sqlStatement)

Returns a PDO prepared statement to be executed with ‘executePrepared’

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes)

Executes a prepared statement binding. This function uses integer indexes starting from zero

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public query (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes])

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data
$resultset = $connection->query("SELECT * FROM robots WHERE type='mechanical'");
$resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical"));

public execute (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes])

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn’t return any rows

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public affectedRows ()

Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system

<?php

$connection->execute("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public close ()

Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends

public string escapeIdentifier (string $identifier)

Escapes a column/table/schema name

<?php

$escapedTable = $connection->escapeIdentifier('robots');
$escapedTable = $connection->escapeIdentifier(['store', 'robots']);

public escapeString (mixed $str)

Escapes a value to avoid SQL injections according to the active charset in the connection

<?php

$escapedStr = $connection->escapeString('some dangerous value');

public convertBoundParams (mixed $sql, [array $params])

Converts bound parameters such as :name: or ?1 into PDO bind params ?

<?php

 print_r($connection->convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender')));

public int | boolean lastInsertId ([string $sequenceName])

Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Getting the generated id
 $id = $connection->lastInsertId();

public begin ([mixed $nesting])

Starts a transaction in the connection

public rollback ([mixed $nesting])

Rollbacks the active transaction in the connection

public commit ([mixed $nesting])

Commits the active transaction in the connection

public getTransactionLevel ()

Returns the current transaction nesting level

public isUnderTransaction ()

Checks whether the connection is under a transaction

<?php

$connection->begin();
var_dump($connection->isUnderTransaction()); //true

public getInternalHandler ()

Return internal PDO handler

public array getErrorInfo ()

Return the error info, if any

public getDialectType () inherited from Phalcon\Db\Adapter

Name of the dialect used

public getType () inherited from Phalcon\Db\Adapter

Type of database system the adapter is used for

public getSqlVariables () inherited from Phalcon\Db\Adapter

Active SQL bound parameter variables

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public setDialect (Phalcon\Db\DialectInterface $dialect) inherited from Phalcon\Db\Adapter

Sets the dialect used to produce the SQL

public getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fetchOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, [int $fetchMode], [array $bindParams], [array $bindTypes]) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}

public string | ** fetchColumn (string $sqlQuery, [array $placeholders], [int | string $column]) inherited from Phalcon\Db\Adapter

Returns the n’th field of first row in a SQL query result

<?php

//Getting count of robots
$robotsCount = $connection->fetchColumn("SELECT count(*) FROM robots");
print_r($robotsCount);

//Getting name of last edited robot
$robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1);
print_r($robot);

public boolean insert (string | array $table, array $values, [array $fields], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RDBMS SQL syntax

<?php

 // Inserting a new robot
 $success = $connection->insert(
 "robots",
 array("Astro Boy", 1952),
 array("name", "year")
 );

 // Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean insertAsDict (string $table, array $data, [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insertAsDict(
 "robots",
 array(
      "name" => "Astro Boy",
      "year" => 1952
  )
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string | array $table, array $fields, array $values, [string | array $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

 //Updating existing robot with array condition and $dataTypes
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 array(
     'conditions' => "id = ?",
     'bind' => array($some_unsafe_id),
     'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param
 ),
 array(PDO::PARAM_STR)
 );

Warning! If $whereCondition is string it not escaped.

public boolean updateAsDict (string $table, array $data, [string $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax

<?php

 //Updating existing robot
 $success = $connection->updateAsDict(
 "robots",
 array(
      "name" => "New Astro Boy"
  ),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string | array $table, [string $whereCondition], [array $placeholders], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
 "robots",
 "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

    echo $connection->limit("SELECT * FROM robots", 5);

public tableExists (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

    var_dump($connection->tableExists("blog", "posts"));

public viewExists (mixed $viewName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 var_dump($connection->viewExists("active_users", "posts"));

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public createTable (mixed $tableName, mixed $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public createView (mixed $viewName, array $definition, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Creates a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a view

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn]) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\Adapter

Drops a table’s primary key

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public listTables ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all tables on a database

<?php

    print_r($connection->listTables("blog"));

public listViews ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all views on a database

<?php

print_r($connection->listViews("blog"));

public Phalcon\Db\Index[] describeIndexes (string $table, [string $schema]) inherited from Phalcon\Db\Adapter

Lists table indexes

<?php

print_r($connection->describeIndexes('robots_parts'));

public describeReferences (mixed $table, [mixed $schema]) inherited from Phalcon\Db\Adapter

Lists table references

<?php

 print_r($connection->describeReferences('robots_parts'));

public tableOptions (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Gets creation options from a table

<?php

 print_r($connection->tableOptions('robots'));

public createSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Creates a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Releases given savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Rollbacks given savepoint

public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints) inherited from Phalcon\Db\Adapter

Set if nested transactions should use savepoints

public isNestedTransactionsWithSavepoints () inherited from Phalcon\Db\Adapter

Returns if nested transactions should use savepoints

public getNestedTransactionSavepointName () inherited from Phalcon\Db\Adapter

Returns the savepoint name to use for nested transactions

public getDefaultIdValue () inherited from Phalcon\Db\Adapter

Returns the default identity value to be inserted in an identity column

<?php

 //Inserting a new robot with a valid default value for the column 'id'
 $success = $connection->insert(
 "robots",
 array($connection->getDefaultIdValue(), "Astro Boy", 1952),
 array("id", "name", "year")
 );

public getDefaultValue () inherited from Phalcon\Db\Adapter

Returns the default value to make the RBDM use the default value declared in the table definition

<?php

 //Inserting a new robot with a valid default value for the column 'year'
 $success = $connection->insert(
 "robots",
 array("Astro Boy", $connection->getDefaultValue()),
 array("name", "year")
 );

public supportSequences () inherited from Phalcon\Db\Adapter

Check whether the database system requires a sequence to produce auto-numeric values

public useExplicitIdValue () inherited from Phalcon\Db\Adapter

Check whether the database system requires an explicit value for identity columns

public getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

Class Phalcon\Db\Adapter\Pdo\Mysql

extends abstract class Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Source on GitHub

Specific functions for the Mysql database system

<?php

 use Phalcon\Db\Adapter\Pdo\Mysql;

 $config = [
   'host'     => 'localhost',
   'dbname'   => 'blog',
   'port'     => 3306,
   'username' => 'sigma',
   'password' => 'secret'
 ];

 $connection = new Mysql($config);
Methods

public escapeIdentifier (mixed $identifier)

Escapes a column/table/schema name

<?php

 echo $connection->escapeIdentifier('my_table'); // `my_table`
 echo $connection->escapeIdentifier(['companies', 'name']); // `companies`.`name`
<?php

 @param string|array identifier

public describeColumns (mixed $table, [mixed $schema])

Returns an array of Phalcon\Db\Column objects describing a table

<?php

 print_r($connection->describeColumns("posts"));

public Phalcon\Db\IndexInterface[] describeIndexes (string $table, [string $schema])

Lists table indexes

<?php

   print_r($connection->describeIndexes('robots_parts'));

public describeReferences (mixed $table, [mixed $schema])

Lists table references

<?php

 print_r($connection->describeReferences('robots_parts'));

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public connect ([array $descriptor]) inherited from Phalcon\Db\Adapter\Pdo

This method is automatically called in \Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.

<?php

 use Phalcon\Db\Adapter\Pdo\Mysql;

 // Make a connection
 $connection = new Mysql([
  'host'     => 'localhost',
  'username' => 'sigma',
  'password' => 'secret',
  'dbname'   => 'blog',
  'port'     => 3306,
 ]);

 // Reconnect
 $connection->connect();

public prepare (mixed $sqlStatement) inherited from Phalcon\Db\Adapter\Pdo

Returns a PDO prepared statement to be executed with ‘executePrepared’

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding. This function uses integer indexes starting from zero

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public query (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data
$resultset = $connection->query("SELECT * FROM robots WHERE type='mechanical'");
$resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical"));

public execute (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn’t return any rows

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system

<?php

$connection->execute("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public close () inherited from Phalcon\Db\Adapter\Pdo

Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends

public escapeString (mixed $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections according to the active charset in the connection

<?php

$escapedStr = $connection->escapeString('some dangerous value');

public convertBoundParams (mixed $sql, [array $params]) inherited from Phalcon\Db\Adapter\Pdo

Converts bound parameters such as :name: or ?1 into PDO bind params ?

<?php

 print_r($connection->convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender')));

public int | boolean lastInsertId ([string $sequenceName]) inherited from Phalcon\Db\Adapter\Pdo

Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Getting the generated id
 $id = $connection->lastInsertId();

public begin ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public rollback ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public commit ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public getTransactionLevel () inherited from Phalcon\Db\Adapter\Pdo

Returns the current transaction nesting level

public isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether the connection is under a transaction

<?php

$connection->begin();
var_dump($connection->isUnderTransaction()); //true

public getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public array getErrorInfo () inherited from Phalcon\Db\Adapter\Pdo

Return the error info, if any

public getDialectType () inherited from Phalcon\Db\Adapter

Name of the dialect used

public getType () inherited from Phalcon\Db\Adapter

Type of database system the adapter is used for

public getSqlVariables () inherited from Phalcon\Db\Adapter

Active SQL bound parameter variables

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public setDialect (Phalcon\Db\DialectInterface $dialect) inherited from Phalcon\Db\Adapter

Sets the dialect used to produce the SQL

public getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fetchOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, [int $fetchMode], [array $bindParams], [array $bindTypes]) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}

public string | ** fetchColumn (string $sqlQuery, [array $placeholders], [int | string $column]) inherited from Phalcon\Db\Adapter

Returns the n’th field of first row in a SQL query result

<?php

//Getting count of robots
$robotsCount = $connection->fetchColumn("SELECT count(*) FROM robots");
print_r($robotsCount);

//Getting name of last edited robot
$robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1);
print_r($robot);

public boolean insert (string | array $table, array $values, [array $fields], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RDBMS SQL syntax

<?php

 // Inserting a new robot
 $success = $connection->insert(
 "robots",
 array("Astro Boy", 1952),
 array("name", "year")
 );

 // Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean insertAsDict (string $table, array $data, [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insertAsDict(
 "robots",
 array(
      "name" => "Astro Boy",
      "year" => 1952
  )
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string | array $table, array $fields, array $values, [string | array $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

 //Updating existing robot with array condition and $dataTypes
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 array(
     'conditions' => "id = ?",
     'bind' => array($some_unsafe_id),
     'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param
 ),
 array(PDO::PARAM_STR)
 );

Warning! If $whereCondition is string it not escaped.

public boolean updateAsDict (string $table, array $data, [string $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax

<?php

 //Updating existing robot
 $success = $connection->updateAsDict(
 "robots",
 array(
      "name" => "New Astro Boy"
  ),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string | array $table, [string $whereCondition], [array $placeholders], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
 "robots",
 "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

    echo $connection->limit("SELECT * FROM robots", 5);

public tableExists (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

    var_dump($connection->tableExists("blog", "posts"));

public viewExists (mixed $viewName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 var_dump($connection->viewExists("active_users", "posts"));

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public createTable (mixed $tableName, mixed $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public createView (mixed $viewName, array $definition, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Creates a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a view

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn]) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\Adapter

Drops a table’s primary key

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public listTables ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all tables on a database

<?php

    print_r($connection->listTables("blog"));

public listViews ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all views on a database

<?php

print_r($connection->listViews("blog"));

public tableOptions (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Gets creation options from a table

<?php

 print_r($connection->tableOptions('robots'));

public createSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Creates a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Releases given savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Rollbacks given savepoint

public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints) inherited from Phalcon\Db\Adapter

Set if nested transactions should use savepoints

public isNestedTransactionsWithSavepoints () inherited from Phalcon\Db\Adapter

Returns if nested transactions should use savepoints

public getNestedTransactionSavepointName () inherited from Phalcon\Db\Adapter

Returns the savepoint name to use for nested transactions

public getDefaultIdValue () inherited from Phalcon\Db\Adapter

Returns the default identity value to be inserted in an identity column

<?php

 //Inserting a new robot with a valid default value for the column 'id'
 $success = $connection->insert(
 "robots",
 array($connection->getDefaultIdValue(), "Astro Boy", 1952),
 array("id", "name", "year")
 );

public getDefaultValue () inherited from Phalcon\Db\Adapter

Returns the default value to make the RBDM use the default value declared in the table definition

<?php

 //Inserting a new robot with a valid default value for the column 'year'
 $success = $connection->insert(
 "robots",
 array("Astro Boy", $connection->getDefaultValue()),
 array("name", "year")
 );

public supportSequences () inherited from Phalcon\Db\Adapter

Check whether the database system requires a sequence to produce auto-numeric values

public useExplicitIdValue () inherited from Phalcon\Db\Adapter

Check whether the database system requires an explicit value for identity columns

public getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

Class Phalcon\Db\Adapter\Pdo\Postgresql

extends abstract class Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Source on GitHub

Specific functions for the Postgresql database system

<?php

 use Phalcon\Db\Adapter\Pdo\Postgresql;

 $config = [
   'host'     => 'localhost',
   'dbname'   => 'blog',
   'port'     => 5432,
   'username' => 'postgres',
   'password' => 'secret'
 ];

 $connection = new Postgresql($config);
Methods

public connect ([array $descriptor])

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.

public describeColumns (mixed $table, [mixed $schema])

Returns an array of Phalcon\Db\Column objects describing a table

<?php

 print_r($connection->describeColumns("posts"));

public createTable (mixed $tableName, mixed $schemaName, array $definition)

Creates a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

Modifies a table column based on a definition

public useExplicitIdValue ()

Check whether the database system requires an explicit value for identity columns

public getDefaultIdValue ()

Returns the default identity value to be inserted in an identity column

<?php

 //Inserting a new robot with a valid default value for the column 'id'
 $success = $connection->insert(
     "robots",
     array($connection->getDefaultIdValue(), "Astro Boy", 1952),
     array("id", "name", "year")
 );

public supportSequences ()

Check whether the database system requires a sequence to produce auto-numeric values

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public prepare (mixed $sqlStatement) inherited from Phalcon\Db\Adapter\Pdo

Returns a PDO prepared statement to be executed with ‘executePrepared’

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding. This function uses integer indexes starting from zero

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public query (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data
$resultset = $connection->query("SELECT * FROM robots WHERE type='mechanical'");
$resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical"));

public execute (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn’t return any rows

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system

<?php

$connection->execute("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public close () inherited from Phalcon\Db\Adapter\Pdo

Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends

public string escapeIdentifier (string $identifier) inherited from Phalcon\Db\Adapter\Pdo

Escapes a column/table/schema name

<?php

$escapedTable = $connection->escapeIdentifier('robots');
$escapedTable = $connection->escapeIdentifier(['store', 'robots']);

public escapeString (mixed $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections according to the active charset in the connection

<?php

$escapedStr = $connection->escapeString('some dangerous value');

public convertBoundParams (mixed $sql, [array $params]) inherited from Phalcon\Db\Adapter\Pdo

Converts bound parameters such as :name: or ?1 into PDO bind params ?

<?php

 print_r($connection->convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender')));

public int | boolean lastInsertId ([string $sequenceName]) inherited from Phalcon\Db\Adapter\Pdo

Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Getting the generated id
 $id = $connection->lastInsertId();

public begin ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public rollback ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public commit ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public getTransactionLevel () inherited from Phalcon\Db\Adapter\Pdo

Returns the current transaction nesting level

public isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether the connection is under a transaction

<?php

$connection->begin();
var_dump($connection->isUnderTransaction()); //true

public getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public array getErrorInfo () inherited from Phalcon\Db\Adapter\Pdo

Return the error info, if any

public getDialectType () inherited from Phalcon\Db\Adapter

Name of the dialect used

public getType () inherited from Phalcon\Db\Adapter

Type of database system the adapter is used for

public getSqlVariables () inherited from Phalcon\Db\Adapter

Active SQL bound parameter variables

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public setDialect (Phalcon\Db\DialectInterface $dialect) inherited from Phalcon\Db\Adapter

Sets the dialect used to produce the SQL

public getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fetchOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, [int $fetchMode], [array $bindParams], [array $bindTypes]) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}

public string | ** fetchColumn (string $sqlQuery, [array $placeholders], [int | string $column]) inherited from Phalcon\Db\Adapter

Returns the n’th field of first row in a SQL query result

<?php

//Getting count of robots
$robotsCount = $connection->fetchColumn("SELECT count(*) FROM robots");
print_r($robotsCount);

//Getting name of last edited robot
$robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1);
print_r($robot);

public boolean insert (string | array $table, array $values, [array $fields], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RDBMS SQL syntax

<?php

 // Inserting a new robot
 $success = $connection->insert(
 "robots",
 array("Astro Boy", 1952),
 array("name", "year")
 );

 // Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean insertAsDict (string $table, array $data, [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insertAsDict(
 "robots",
 array(
      "name" => "Astro Boy",
      "year" => 1952
  )
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string | array $table, array $fields, array $values, [string | array $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

 //Updating existing robot with array condition and $dataTypes
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 array(
     'conditions' => "id = ?",
     'bind' => array($some_unsafe_id),
     'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param
 ),
 array(PDO::PARAM_STR)
 );

Warning! If $whereCondition is string it not escaped.

public boolean updateAsDict (string $table, array $data, [string $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax

<?php

 //Updating existing robot
 $success = $connection->updateAsDict(
 "robots",
 array(
      "name" => "New Astro Boy"
  ),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string | array $table, [string $whereCondition], [array $placeholders], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
 "robots",
 "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

    echo $connection->limit("SELECT * FROM robots", 5);

public tableExists (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

    var_dump($connection->tableExists("blog", "posts"));

public viewExists (mixed $viewName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 var_dump($connection->viewExists("active_users", "posts"));

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public createView (mixed $viewName, array $definition, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Creates a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a view

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\Adapter

Drops a table’s primary key

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public listTables ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all tables on a database

<?php

    print_r($connection->listTables("blog"));

public listViews ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all views on a database

<?php

print_r($connection->listViews("blog"));

public Phalcon\Db\Index[] describeIndexes (string $table, [string $schema]) inherited from Phalcon\Db\Adapter

Lists table indexes

<?php

print_r($connection->describeIndexes('robots_parts'));

public describeReferences (mixed $table, [mixed $schema]) inherited from Phalcon\Db\Adapter

Lists table references

<?php

 print_r($connection->describeReferences('robots_parts'));

public tableOptions (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Gets creation options from a table

<?php

 print_r($connection->tableOptions('robots'));

public createSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Creates a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Releases given savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Rollbacks given savepoint

public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints) inherited from Phalcon\Db\Adapter

Set if nested transactions should use savepoints

public isNestedTransactionsWithSavepoints () inherited from Phalcon\Db\Adapter

Returns if nested transactions should use savepoints

public getNestedTransactionSavepointName () inherited from Phalcon\Db\Adapter

Returns the savepoint name to use for nested transactions

public getDefaultValue () inherited from Phalcon\Db\Adapter

Returns the default value to make the RBDM use the default value declared in the table definition

<?php

 //Inserting a new robot with a valid default value for the column 'year'
 $success = $connection->insert(
 "robots",
 array("Astro Boy", $connection->getDefaultValue()),
 array("name", "year")
 );

public getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

Class Phalcon\Db\Adapter\Pdo\Sqlite

extends abstract class Phalcon\Db\Adapter\Pdo

implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface

Source on GitHub

Specific functions for the Sqlite database system

<?php

 use Phalcon\Db\Adapter\Pdo\Sqlite;

 $connection = new Sqlite(['dbname' => '/tmp/test.sqlite']);
Methods

public connect ([array $descriptor])

This method is automatically called in Phalcon\Db\Adapter\Pdo constructor. Call it when you need to restore a database connection.

public describeColumns (mixed $table, [mixed $schema])

Returns an array of Phalcon\Db\Column objects describing a table

<?php

 print_r($connection->describeColumns("posts"));

public Phalcon\Db\IndexInterface[] describeIndexes (string $table, [string $schema])

Lists table indexes

<?php

   print_r($connection->describeIndexes('robots_parts'));

public Phalcon\Db\ReferenceInterface[] describeReferences (string $table, [string $schema])

Lists table references

public useExplicitIdValue ()

Check whether the database system requires an explicit value for identity columns

public getDefaultValue ()

Returns the default value to make the RBDM use the default value declared in the table definition

<?php

 //Inserting a new robot with a valid default value for the column 'year'
 $success = $connection->insert(
 "robots",
 array("Astro Boy", $connection->getDefaultValue()),
 array("name", "year")
 );

public __construct (array $descriptor) inherited from Phalcon\Db\Adapter\Pdo

Constructor for Phalcon\Db\Adapter\Pdo

public prepare (mixed $sqlStatement) inherited from Phalcon\Db\Adapter\Pdo

Returns a PDO prepared statement to be executed with ‘executePrepared’

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public PDOStatement executePrepared (PDOStatement $statement, array $placeholders, array $dataTypes) inherited from Phalcon\Db\Adapter\Pdo

Executes a prepared statement binding. This function uses integer indexes starting from zero

<?php

 use Phalcon\Db\Column;

 $statement = $db->prepare('SELECT * FROM robots WHERE name = :name');
 $result = $connection->executePrepared($statement, ['name' => 'Voltron'], ['name' => Column::BIND_PARAM_INT]);

public query (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server is returning rows

<?php

//Querying data
$resultset = $connection->query("SELECT * FROM robots WHERE type='mechanical'");
$resultset = $connection->query("SELECT * FROM robots WHERE type=?", array("mechanical"));

public execute (mixed $sqlStatement, [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter\Pdo

Sends SQL statements to the database server returning the success state. Use this method only when the SQL statement sent to the server doesn’t return any rows

<?php

//Inserting data
$success = $connection->execute("INSERT INTO robots VALUES (1, 'Astro Boy')");
$success = $connection->execute("INSERT INTO robots VALUES (?, ?)", array(1, 'Astro Boy'));

public affectedRows () inherited from Phalcon\Db\Adapter\Pdo

Returns the number of affected rows by the lastest INSERT/UPDATE/DELETE executed in the database system

<?php

$connection->execute("DELETE FROM robots");
echo $connection->affectedRows(), ' were deleted';

public close () inherited from Phalcon\Db\Adapter\Pdo

Closes the active connection returning success. Phalcon automatically closes and destroys active connections when the request ends

public string escapeIdentifier (string $identifier) inherited from Phalcon\Db\Adapter\Pdo

Escapes a column/table/schema name

<?php

$escapedTable = $connection->escapeIdentifier('robots');
$escapedTable = $connection->escapeIdentifier(['store', 'robots']);

public escapeString (mixed $str) inherited from Phalcon\Db\Adapter\Pdo

Escapes a value to avoid SQL injections according to the active charset in the connection

<?php

$escapedStr = $connection->escapeString('some dangerous value');

public convertBoundParams (mixed $sql, [array $params]) inherited from Phalcon\Db\Adapter\Pdo

Converts bound parameters such as :name: or ?1 into PDO bind params ?

<?php

 print_r($connection->convertBoundParams('SELECT * FROM robots WHERE name = :name:', array('Bender')));

public int | boolean lastInsertId ([string $sequenceName]) inherited from Phalcon\Db\Adapter\Pdo

Returns the insert id for the auto_increment/serial column inserted in the lastest executed SQL statement

<?php

 //Inserting a new robot
 $success = $connection->insert(
     "robots",
     array("Astro Boy", 1952),
     array("name", "year")
 );

 //Getting the generated id
 $id = $connection->lastInsertId();

public begin ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Starts a transaction in the connection

public rollback ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Rollbacks the active transaction in the connection

public commit ([mixed $nesting]) inherited from Phalcon\Db\Adapter\Pdo

Commits the active transaction in the connection

public getTransactionLevel () inherited from Phalcon\Db\Adapter\Pdo

Returns the current transaction nesting level

public isUnderTransaction () inherited from Phalcon\Db\Adapter\Pdo

Checks whether the connection is under a transaction

<?php

$connection->begin();
var_dump($connection->isUnderTransaction()); //true

public getInternalHandler () inherited from Phalcon\Db\Adapter\Pdo

Return internal PDO handler

public array getErrorInfo () inherited from Phalcon\Db\Adapter\Pdo

Return the error info, if any

public getDialectType () inherited from Phalcon\Db\Adapter

Name of the dialect used

public getType () inherited from Phalcon\Db\Adapter

Type of database system the adapter is used for

public getSqlVariables () inherited from Phalcon\Db\Adapter

Active SQL bound parameter variables

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Db\Adapter

Sets the event manager

public getEventsManager () inherited from Phalcon\Db\Adapter

Returns the internal event manager

public setDialect (Phalcon\Db\DialectInterface $dialect) inherited from Phalcon\Db\Adapter

Sets the dialect used to produce the SQL

public getDialect () inherited from Phalcon\Db\Adapter

Returns internal dialect instance

public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $bindParams], [mixed $bindTypes]) inherited from Phalcon\Db\Adapter

Returns the first row in a SQL query result

<?php

//Getting first robot
$robot = $connection->fetchOne("SELECT * FROM robots");
print_r($robot);

//Getting first robot with associative indexes only
$robot = $connection->fetchOne("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
print_r($robot);

public array fetchAll (string $sqlQuery, [int $fetchMode], [array $bindParams], [array $bindTypes]) inherited from Phalcon\Db\Adapter

Dumps the complete result of a query into an array

<?php

//Getting all robots with associative indexes only
$robots = $connection->fetchAll("SELECT * FROM robots", Phalcon\Db::FETCH_ASSOC);
foreach ($robots as $robot) {
    print_r($robot);
}

  //Getting all robots that contains word "robot" withing the name
  $robots = $connection->fetchAll("SELECT * FROM robots WHERE name LIKE :name",
    Phalcon\Db::FETCH_ASSOC,
    array('name' => '%robot%')
  );
foreach($robots as $robot){
    print_r($robot);
}

public string | ** fetchColumn (string $sqlQuery, [array $placeholders], [int | string $column]) inherited from Phalcon\Db\Adapter

Returns the n’th field of first row in a SQL query result

<?php

//Getting count of robots
$robotsCount = $connection->fetchColumn("SELECT count(*) FROM robots");
print_r($robotsCount);

//Getting name of last edited robot
$robot = $connection->fetchColumn("SELECT id, name FROM robots order by modified desc", 1);
print_r($robot);

public boolean insert (string | array $table, array $values, [array $fields], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RDBMS SQL syntax

<?php

 // Inserting a new robot
 $success = $connection->insert(
 "robots",
 array("Astro Boy", 1952),
 array("name", "year")
 );

 // Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean insertAsDict (string $table, array $data, [array $dataTypes]) inherited from Phalcon\Db\Adapter

Inserts data into a table using custom RBDM SQL syntax

<?php

 //Inserting a new robot
 $success = $connection->insertAsDict(
 "robots",
 array(
      "name" => "Astro Boy",
      "year" => 1952
  )
 );

 //Next SQL sentence is sent to the database system
 INSERT INTO `robots` (`name`, `year`) VALUES ("Astro boy", 1952);

public boolean update (string | array $table, array $fields, array $values, [string | array $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax

<?php

 //Updating existing robot
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

 //Updating existing robot with array condition and $dataTypes
 $success = $connection->update(
 "robots",
 array("name"),
 array("New Astro Boy"),
 array(
     'conditions' => "id = ?",
     'bind' => array($some_unsafe_id),
     'bindTypes' => array(PDO::PARAM_INT) //use only if you use $dataTypes param
 ),
 array(PDO::PARAM_STR)
 );

Warning! If $whereCondition is string it not escaped.

public boolean updateAsDict (string $table, array $data, [string $whereCondition], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Updates data on a table using custom RBDM SQL syntax Another, more convenient syntax

<?php

 //Updating existing robot
 $success = $connection->updateAsDict(
 "robots",
 array(
      "name" => "New Astro Boy"
  ),
 "id = 101"
 );

 //Next SQL sentence is sent to the database system
 UPDATE `robots` SET `name` = "Astro boy" WHERE id = 101

public boolean delete (string | array $table, [string $whereCondition], [array $placeholders], [array $dataTypes]) inherited from Phalcon\Db\Adapter

Deletes data from a table using custom RBDM SQL syntax

<?php

 //Deleting existing robot
 $success = $connection->delete(
 "robots",
 "id = 101"
 );

 //Next SQL sentence is generated
 DELETE FROM `robots` WHERE `id` = 101

public string getColumnList (array $columnList) inherited from Phalcon\Db\Adapter

Gets a list of columns

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Adapter

Appends a LIMIT clause to $sqlQuery argument

<?php

    echo $connection->limit("SELECT * FROM robots", 5);

public tableExists (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.table

<?php

    var_dump($connection->tableExists("blog", "posts"));

public viewExists (mixed $viewName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Generates SQL checking for the existence of a schema.view

<?php

 var_dump($connection->viewExists("active_users", "posts"));

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a FOR UPDATE clause

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Adapter

Returns a SQL modified with a LOCK IN SHARE MODE clause

public createTable (mixed $tableName, mixed $schemaName, array $definition) inherited from Phalcon\Db\Adapter

Creates a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a table from a schema/database

public createView (mixed $viewName, array $definition, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Creates a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\Adapter

Drops a view

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Adds a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn]) inherited from Phalcon\Db\Adapter

Modifies a table column based on a definition

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName) inherited from Phalcon\Db\Adapter

Drops a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName) inherited from Phalcon\Db\Adapter

Drop an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\Adapter

Adds a primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\Adapter

Drops a table’s primary key

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\Adapter

Adds a foreign key to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName) inherited from Phalcon\Db\Adapter

Drops a foreign key from a table

public getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\Adapter

Returns the SQL column definition from a column

public listTables ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all tables on a database

<?php

    print_r($connection->listTables("blog"));

public listViews ([mixed $schemaName]) inherited from Phalcon\Db\Adapter

List all views on a database

<?php

print_r($connection->listViews("blog"));

public tableOptions (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\Adapter

Gets creation options from a table

<?php

 print_r($connection->tableOptions('robots'));

public createSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Creates a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Releases given savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Adapter

Rollbacks given savepoint

public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints) inherited from Phalcon\Db\Adapter

Set if nested transactions should use savepoints

public isNestedTransactionsWithSavepoints () inherited from Phalcon\Db\Adapter

Returns if nested transactions should use savepoints

public getNestedTransactionSavepointName () inherited from Phalcon\Db\Adapter

Returns the savepoint name to use for nested transactions

public getDefaultIdValue () inherited from Phalcon\Db\Adapter

Returns the default identity value to be inserted in an identity column

<?php

 //Inserting a new robot with a valid default value for the column 'id'
 $success = $connection->insert(
 "robots",
 array($connection->getDefaultIdValue(), "Astro Boy", 1952),
 array("id", "name", "year")
 );

public supportSequences () inherited from Phalcon\Db\Adapter

Check whether the database system requires a sequence to produce auto-numeric values

public getDescriptor () inherited from Phalcon\Db\Adapter

Return descriptor used to connect to the active database

public string getConnectionId () inherited from Phalcon\Db\Adapter

Gets the active connection unique identifier

public getSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

public getRealSQLStatement () inherited from Phalcon\Db\Adapter

Active SQL statement in the object without replace bound paramters

public array getSQLBindTypes () inherited from Phalcon\Db\Adapter

Active SQL statement in the object

Class Phalcon\Db\Column

implements Phalcon\Db\ColumnInterface

Source on GitHub

Allows to define columns to be used on create or alter table operations

<?php

use Phalcon\Db\Column as Column;

 //column definition
 $column = new Column("id", array(
   "type" => Column::TYPE_INTEGER,
   "size" => 10,
   "unsigned" => true,
   "notNull" => true,
   "autoIncrement" => true,
   "first" => true
 ));

 //add column to existing table
 $connection->addColumn("robots", null, $column);
Constants

integer TYPE_INTEGER

integer TYPE_DATE

integer TYPE_VARCHAR

integer TYPE_DECIMAL

integer TYPE_DATETIME

integer TYPE_CHAR

integer TYPE_TEXT

integer TYPE_FLOAT

integer TYPE_BOOLEAN

integer TYPE_DOUBLE

integer TYPE_TINYBLOB

integer TYPE_BLOB

integer TYPE_MEDIUMBLOB

integer TYPE_LONGBLOB

integer TYPE_BIGINTEGER

integer TYPE_JSON

integer TYPE_JSONB

integer TYPE_TIMESTAMP

integer BIND_PARAM_NULL

integer BIND_PARAM_INT

integer BIND_PARAM_STR

integer BIND_PARAM_BLOB

integer BIND_PARAM_BOOL

integer BIND_PARAM_DECIMAL

integer BIND_SKIP

Methods

public getName ()

Column’s name

public getSchemaName ()

Schema which table related is

public getType ()

Column data type

public getTypeReference ()

Column data type reference

public getTypeValues ()

Column data type values

public getSize ()

Integer column size

public getScale ()

Integer column number scale

public getDefault ()

Default column value

public __construct (mixed $name, array $definition)

Phalcon\Db\Column constructor

public isUnsigned ()

Returns true if number column is unsigned

public isNotNull ()

Not null

public isPrimary ()

Column is part of the primary key?

public isAutoIncrement ()

Auto-Increment

public isNumeric ()

Check whether column have an numeric type

public isFirst ()

Check whether column have first position in table

public string getAfterPosition ()

Check whether field absolute to position in table

public getBindType ()

Returns the type of bind handling

public static __set_state (array $data)

Restores the internal state of a Phalcon\Db\Column object

public hasDefault ()

Check whether column has default value

Abstract class Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Source on GitHub

This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax

Methods

public registerCustomFunction (mixed $name, mixed $customFunction)

Registers custom SQL functions

public getCustomFunctions ()

Returns registered functions

final public escapeSchema (mixed $str, [mixed $escapeChar])

Escape Schema

final public escape (mixed $str, [mixed $escapeChar])

Escape identifiers

public limit (mixed $sqlQuery, mixed $number)

Generates the SQL for LIMIT clause

<?php

    $sql = $dialect->limit('SELECT * FROM robots', 10);
    echo $sql; // SELECT * FROM robots LIMIT 10

    $sql = $dialect->limit('SELECT * FROM robots', [10, 50]);
    echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50

public forUpdate (mixed $sqlQuery)

Returns a SQL modified with a FOR UPDATE clause

<?php

 $sql = $dialect->forUpdate('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots FOR UPDATE

public sharedLock (mixed $sqlQuery)

Returns a SQL modified with a LOCK IN SHARE MODE clause

<?php

 $sql = $dialect->sharedLock('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE

final public getColumnList (array $columnList, [mixed $escapeChar], [mixed $bindCounts])

Gets a list of columns with escaped identifiers

<?php

    echo $dialect->getColumnList(array('column1', 'column'));

final public getSqlColumn (mixed $column, [mixed $escapeChar], [mixed $bindCounts])

Resolve Column expressions

public getSqlExpression (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Transforms an intermediate representation for an expression into a database system valid expression

final public getSqlTable (mixed $table, [mixed $escapeChar])

Transform an intermediate representation of a schema/table into a database system valid expression

public select (array $definition)

Builds a SELECT statement

public supportsSavepoints ()

Checks whether the platform supports savepoints

public supportsReleaseSavepoints ()

Checks whether the platform supports releasing savepoints.

public createSavepoint (mixed $name)

Generate SQL to create a new savepoint

public releaseSavepoint (mixed $name)

Generate SQL to release a savepoint

public rollbackSavepoint (mixed $name)

Generate SQL to rollback a savepoint

final protected getSqlExpressionScalar (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve Column expressions

final protected getSqlExpressionObject (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve object expressions

final protected getSqlExpressionQualified (array $expression, [mixed $escapeChar])

Resolve qualified expressions

final protected getSqlExpressionBinaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve binary operations expressions

final protected getSqlExpressionUnaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve unary operations expressions

final protected getSqlExpressionFunctionCall (array $expression, mixed $escapeChar, [mixed $bindCounts])

Resolve function calls

final protected getSqlExpressionList (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve Lists

final protected getSqlExpressionAll (array $expression, [mixed $escapeChar])

Resolve *

final protected getSqlExpressionCastValue (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve CAST of values

final protected getSqlExpressionConvertValue (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve CONVERT of values encodings

final protected getSqlExpressionCase (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve CASE expressions

final protected getSqlExpressionFrom (mixed $expression, [mixed $escapeChar])

Resolve a FROM clause

final protected getSqlExpressionJoins (mixed $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve a JOINs clause

final protected getSqlExpressionWhere (mixed $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve a WHERE clause

final protected getSqlExpressionGroupBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve a GROUP BY clause

final protected getSqlExpressionHaving (array $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve a HAVING clause

final protected getSqlExpressionOrderBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve an ORDER BY clause

final protected getSqlExpressionLimit (mixed $expression, [mixed $escapeChar], [mixed $bindCounts])

Resolve a LIMIT clause

protected prepareColumnAlias (mixed $qualified, [mixed $alias], [mixed $escapeChar])

Prepares column for this RDBMS

protected prepareTable (mixed $table, [mixed $schema], [mixed $alias], [mixed $escapeChar])

Prepares table for this RDBMS

protected prepareQualified (mixed $column, [mixed $domain], [mixed $escapeChar])

Prepares qualified for this RDBMS

abstract public getColumnDefinition (Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\DialectInterface

...

abstract public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column) inherited from Phalcon\Db\DialectInterface

...

abstract public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn]) inherited from Phalcon\Db\DialectInterface

...

abstract public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName) inherited from Phalcon\Db\DialectInterface

...

abstract public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\DialectInterface

...

abstract public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName) inherited from Phalcon\Db\DialectInterface

...

abstract public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index) inherited from Phalcon\Db\DialectInterface

...

abstract public dropPrimaryKey (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\DialectInterface

...

abstract public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference) inherited from Phalcon\Db\DialectInterface

...

abstract public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName) inherited from Phalcon\Db\DialectInterface

...

abstract public createTable (mixed $tableName, mixed $schemaName, array $definition) inherited from Phalcon\Db\DialectInterface

...

abstract public createView (mixed $viewName, array $definition, [mixed $schemaName]) inherited from Phalcon\Db\DialectInterface

...

abstract public dropTable (mixed $tableName, mixed $schemaName) inherited from Phalcon\Db\DialectInterface

...

abstract public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists]) inherited from Phalcon\Db\DialectInterface

...

abstract public tableExists (mixed $tableName, [mixed $schemaName]) inherited from Phalcon\Db\DialectInterface

...

abstract public viewExists (mixed $viewName, [mixed $schemaName]) inherited from Phalcon\Db\DialectInterface

...

abstract public describeColumns (mixed $table, [mixed $schema]) inherited from Phalcon\Db\DialectInterface

...

abstract public listTables ([mixed $schemaName]) inherited from Phalcon\Db\DialectInterface

...

abstract public describeIndexes (mixed $table, [mixed $schema]) inherited from Phalcon\Db\DialectInterface

...

abstract public describeReferences (mixed $table, [mixed $schema]) inherited from Phalcon\Db\DialectInterface

...

abstract public tableOptions (mixed $table, [mixed $schema]) inherited from Phalcon\Db\DialectInterface

...

Class Phalcon\Db\Dialect\Mysql

extends abstract class Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Source on GitHub

Generates database specific SQL for the MySQL RDBMS

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in MySQL

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

Generates SQL to modify a column in a table

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

Generates SQL to delete a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

Generates SQL to delete an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName)

Generates SQL to delete primary key from a table

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

Generates SQL to delete a foreign key from a table

public createTable (mixed $tableName, mixed $schemaName, array $definition)

Generates SQL to create a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a table

public createView (mixed $viewName, array $definition, [mixed $schemaName])

Generates SQL to create a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a view

public tableExists (mixed $tableName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.table

<?php

    echo $dialect->tableExists("posts", "blog");
    echo $dialect->tableExists("posts");

public viewExists (mixed $viewName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.view

public describeColumns (mixed $table, [mixed $schema])

Generates SQL describing a table

<?php

    print_r($dialect->describeColumns("posts"));

public listTables ([mixed $schemaName])

List all tables in database

<?php

     print_r($dialect->listTables("blog"))

public listViews ([mixed $schemaName])

Generates the SQL to list all views of a schema or user

public describeIndexes (mixed $table, [mixed $schema])

Generates SQL to query indexes on a table

public describeReferences (mixed $table, [mixed $schema])

Generates SQL to query foreign keys on a table

public tableOptions (mixed $table, [mixed $schema])

Generates the SQL to describe the table creation options

protected _getTableOptions (array $definition)

Generates SQL to add the table creation options

public registerCustomFunction (mixed $name, mixed $customFunction) inherited from Phalcon\Db\Dialect

Registers custom SQL functions

public getCustomFunctions () inherited from Phalcon\Db\Dialect

Returns registered functions

final public escapeSchema (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape Schema

final public escape (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape identifiers

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

<?php

    $sql = $dialect->limit('SELECT * FROM robots', 10);
    echo $sql; // SELECT * FROM robots LIMIT 10

    $sql = $dialect->limit('SELECT * FROM robots', [10, 50]);
    echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

<?php

 $sql = $dialect->forUpdate('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots FOR UPDATE

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

<?php

 $sql = $dialect->sharedLock('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE

final public getColumnList (array $columnList, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Gets a list of columns with escaped identifiers

<?php

    echo $dialect->getColumnList(array('column1', 'column'));

final public getSqlColumn (mixed $column, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

public getSqlExpression (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Transforms an intermediate representation for an expression into a database system valid expression

final public getSqlTable (mixed $table, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Transform an intermediate representation of a schema/table into a database system valid expression

public select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

public supportsSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports savepoints

public supportsReleaseSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports releasing savepoints.

public createSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to create a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to release a savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to rollback a savepoint

final protected getSqlExpressionScalar (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

final protected getSqlExpressionObject (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve object expressions

final protected getSqlExpressionQualified (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve qualified expressions

final protected getSqlExpressionBinaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve binary operations expressions

final protected getSqlExpressionUnaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve unary operations expressions

final protected getSqlExpressionFunctionCall (array $expression, mixed $escapeChar, [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve function calls

final protected getSqlExpressionList (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Lists

final protected getSqlExpressionAll (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve *

final protected getSqlExpressionCastValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CAST of values

final protected getSqlExpressionConvertValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CONVERT of values encodings

final protected getSqlExpressionCase (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CASE expressions

final protected getSqlExpressionFrom (mixed $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve a FROM clause

final protected getSqlExpressionJoins (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a JOINs clause

final protected getSqlExpressionWhere (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a WHERE clause

final protected getSqlExpressionGroupBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a GROUP BY clause

final protected getSqlExpressionHaving (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a HAVING clause

final protected getSqlExpressionOrderBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve an ORDER BY clause

final protected getSqlExpressionLimit (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a LIMIT clause

protected prepareColumnAlias (mixed $qualified, [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares column for this RDBMS

protected prepareTable (mixed $table, [mixed $schema], [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares table for this RDBMS

protected prepareQualified (mixed $column, [mixed $domain], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares qualified for this RDBMS

Class Phalcon\Db\Dialect\Postgresql

extends abstract class Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Source on GitHub

Generates database specific SQL for the PostgreSQL RDBMS

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in PostgreSQL

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

Generates SQL to modify a column in a table

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

Generates SQL to delete a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

Generates SQL to delete an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName)

Generates SQL to delete primary key from a table

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

Generates SQL to delete a foreign key from a table

public createTable (mixed $tableName, mixed $schemaName, array $definition)

Generates SQL to create a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a view

public createView (mixed $viewName, array $definition, [mixed $schemaName])

Generates SQL to create a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a view

public tableExists (mixed $tableName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.table

<?php

    echo $dialect->tableExists("posts", "blog");
    echo $dialect->tableExists("posts");

public viewExists (mixed $viewName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.view

public describeColumns (mixed $table, [mixed $schema])

Generates SQL describing a table

<?php

    print_r($dialect->describeColumns("posts"));

public listTables ([mixed $schemaName])

List all tables in database

<?php

     print_r($dialect->listTables("blog"))

public string listViews ([string $schemaName])

Generates the SQL to list all views of a schema or user

public describeIndexes (mixed $table, [mixed $schema])

Generates SQL to query indexes on a table

public describeReferences (mixed $table, [mixed $schema])

Generates SQL to query foreign keys on a table

public tableOptions (mixed $table, [mixed $schema])

Generates the SQL to describe the table creation options

protected _getTableOptions (array $definition)

...

public registerCustomFunction (mixed $name, mixed $customFunction) inherited from Phalcon\Db\Dialect

Registers custom SQL functions

public getCustomFunctions () inherited from Phalcon\Db\Dialect

Returns registered functions

final public escapeSchema (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape Schema

final public escape (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape identifiers

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

<?php

    $sql = $dialect->limit('SELECT * FROM robots', 10);
    echo $sql; // SELECT * FROM robots LIMIT 10

    $sql = $dialect->limit('SELECT * FROM robots', [10, 50]);
    echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

<?php

 $sql = $dialect->forUpdate('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots FOR UPDATE

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

<?php

 $sql = $dialect->sharedLock('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE

final public getColumnList (array $columnList, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Gets a list of columns with escaped identifiers

<?php

    echo $dialect->getColumnList(array('column1', 'column'));

final public getSqlColumn (mixed $column, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

public getSqlExpression (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Transforms an intermediate representation for an expression into a database system valid expression

final public getSqlTable (mixed $table, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Transform an intermediate representation of a schema/table into a database system valid expression

public select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

public supportsSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports savepoints

public supportsReleaseSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports releasing savepoints.

public createSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to create a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to release a savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to rollback a savepoint

final protected getSqlExpressionScalar (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

final protected getSqlExpressionObject (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve object expressions

final protected getSqlExpressionQualified (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve qualified expressions

final protected getSqlExpressionBinaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve binary operations expressions

final protected getSqlExpressionUnaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve unary operations expressions

final protected getSqlExpressionFunctionCall (array $expression, mixed $escapeChar, [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve function calls

final protected getSqlExpressionList (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Lists

final protected getSqlExpressionAll (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve *

final protected getSqlExpressionCastValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CAST of values

final protected getSqlExpressionConvertValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CONVERT of values encodings

final protected getSqlExpressionCase (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CASE expressions

final protected getSqlExpressionFrom (mixed $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve a FROM clause

final protected getSqlExpressionJoins (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a JOINs clause

final protected getSqlExpressionWhere (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a WHERE clause

final protected getSqlExpressionGroupBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a GROUP BY clause

final protected getSqlExpressionHaving (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a HAVING clause

final protected getSqlExpressionOrderBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve an ORDER BY clause

final protected getSqlExpressionLimit (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a LIMIT clause

protected prepareColumnAlias (mixed $qualified, [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares column for this RDBMS

protected prepareTable (mixed $table, [mixed $schema], [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares table for this RDBMS

protected prepareQualified (mixed $column, [mixed $domain], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares qualified for this RDBMS

Class Phalcon\Db\Dialect\Sqlite

extends abstract class Phalcon\Db\Dialect

implements Phalcon\Db\DialectInterface

Source on GitHub

Generates database specific SQL for the Sqlite RDBMS

Methods

public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

Gets the column name in SQLite

public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

Generates SQL to add a column to a table

public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

Generates SQL to modify a column in a table

public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

Generates SQL to delete a column from a table

public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add an index to a table

public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

Generates SQL to delete an index from a table

public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

Generates SQL to add the primary key to a table

public dropPrimaryKey (mixed $tableName, mixed $schemaName)

Generates SQL to delete primary key from a table

public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

Generates SQL to add an index to a table

public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

Generates SQL to delete a foreign key from a table

public createTable (mixed $tableName, mixed $schemaName, array $definition)

Generates SQL to create a table

public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a table

public createView (mixed $viewName, array $definition, [mixed $schemaName])

Generates SQL to create a view

public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

Generates SQL to drop a view

public tableExists (mixed $tableName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.table

<?php

    echo $dialect->tableExists("posts", "blog");
    echo $dialect->tableExists("posts");

public viewExists (mixed $viewName, [mixed $schemaName])

Generates SQL checking for the existence of a schema.view

public describeColumns (mixed $table, [mixed $schema])

Generates SQL describing a table

<?php

    print_r($dialect->describeColumns("posts"));

public listTables ([mixed $schemaName])

List all tables in database

<?php

     print_r($dialect->listTables("blog"))

public listViews ([mixed $schemaName])

Generates the SQL to list all views of a schema or user

public listIndexesSql (mixed $table, [mixed $schema], [mixed $keyName])

Generates the SQL to get query list of indexes

<?php

     print_r($dialect->listIndexesSql("blog"))

public describeIndexes (mixed $table, [mixed $schema])

Generates SQL to query indexes on a table

public describeIndex (mixed $index)

Generates SQL to query indexes detail on a table

public describeReferences (mixed $table, [mixed $schema])

Generates SQL to query foreign keys on a table

public tableOptions (mixed $table, [mixed $schema])

Generates the SQL to describe the table creation options

public registerCustomFunction (mixed $name, mixed $customFunction) inherited from Phalcon\Db\Dialect

Registers custom SQL functions

public getCustomFunctions () inherited from Phalcon\Db\Dialect

Returns registered functions

final public escapeSchema (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape Schema

final public escape (mixed $str, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Escape identifiers

public limit (mixed $sqlQuery, mixed $number) inherited from Phalcon\Db\Dialect

Generates the SQL for LIMIT clause

<?php

    $sql = $dialect->limit('SELECT * FROM robots', 10);
    echo $sql; // SELECT * FROM robots LIMIT 10

    $sql = $dialect->limit('SELECT * FROM robots', [10, 50]);
    echo $sql; // SELECT * FROM robots LIMIT 10 OFFSET 50

public forUpdate (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a FOR UPDATE clause

<?php

 $sql = $dialect->forUpdate('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots FOR UPDATE

public sharedLock (mixed $sqlQuery) inherited from Phalcon\Db\Dialect

Returns a SQL modified with a LOCK IN SHARE MODE clause

<?php

 $sql = $dialect->sharedLock('SELECT * FROM robots');
 echo $sql; // SELECT * FROM robots LOCK IN SHARE MODE

final public getColumnList (array $columnList, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Gets a list of columns with escaped identifiers

<?php

    echo $dialect->getColumnList(array('column1', 'column'));

final public getSqlColumn (mixed $column, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

public getSqlExpression (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Transforms an intermediate representation for an expression into a database system valid expression

final public getSqlTable (mixed $table, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Transform an intermediate representation of a schema/table into a database system valid expression

public select (array $definition) inherited from Phalcon\Db\Dialect

Builds a SELECT statement

public supportsSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports savepoints

public supportsReleaseSavepoints () inherited from Phalcon\Db\Dialect

Checks whether the platform supports releasing savepoints.

public createSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to create a new savepoint

public releaseSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to release a savepoint

public rollbackSavepoint (mixed $name) inherited from Phalcon\Db\Dialect

Generate SQL to rollback a savepoint

final protected getSqlExpressionScalar (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Column expressions

final protected getSqlExpressionObject (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve object expressions

final protected getSqlExpressionQualified (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve qualified expressions

final protected getSqlExpressionBinaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve binary operations expressions

final protected getSqlExpressionUnaryOperations (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve unary operations expressions

final protected getSqlExpressionFunctionCall (array $expression, mixed $escapeChar, [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve function calls

final protected getSqlExpressionList (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve Lists

final protected getSqlExpressionAll (array $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve *

final protected getSqlExpressionCastValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CAST of values

final protected getSqlExpressionConvertValue (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CONVERT of values encodings

final protected getSqlExpressionCase (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve CASE expressions

final protected getSqlExpressionFrom (mixed $expression, [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Resolve a FROM clause

final protected getSqlExpressionJoins (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a JOINs clause

final protected getSqlExpressionWhere (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a WHERE clause

final protected getSqlExpressionGroupBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a GROUP BY clause

final protected getSqlExpressionHaving (array $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a HAVING clause

final protected getSqlExpressionOrderBy (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve an ORDER BY clause

final protected getSqlExpressionLimit (mixed $expression, [mixed $escapeChar], [mixed $bindCounts]) inherited from Phalcon\Db\Dialect

Resolve a LIMIT clause

protected prepareColumnAlias (mixed $qualified, [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares column for this RDBMS

protected prepareTable (mixed $table, [mixed $schema], [mixed $alias], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares table for this RDBMS

protected prepareQualified (mixed $column, [mixed $domain], [mixed $escapeChar]) inherited from Phalcon\Db\Dialect

Prepares qualified for this RDBMS

Class Phalcon\Db\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Db\Index

implements Phalcon\Db\IndexInterface

Source on GitHub

Allows to define indexes to be used on tables. Indexes are a common way to enhance database performance. An index allows the database server to find and retrieve specific rows much faster than it could do without an index

Methods

public getName ()

Index name

public getColumns ()

Index columns

public getType ()

Index type

public __construct (mixed $name, array $columns, [mixed $type])

Phalcon\Db\Index constructor

public static __set_state (array $data)

Restore a Phalcon\Db\Index object from export

Class Phalcon\Db\Profiler

Source on GitHub

Instances of Phalcon\Db can generate execution profiles on SQL statements sent to the relational database. Profiled information includes execution time in milliseconds. This helps you to identify bottlenecks in your applications.

<?php

$profiler = new \Phalcon\Db\Profiler();

//Set the connection profiler
$connection->setProfiler($profiler);

$sql = "SELECT buyer_name, quantity, product_name
FROM buyers LEFT JOIN products ON
buyers.pid=products.id";

//Execute a SQL statement
$connection->query($sql);

//Get the last profile in the profiler
$profile = $profiler->getLastProfile();

echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
Methods

public Phalcon\Db\Profiler startProfile (string $sqlStatement, [mixed $sqlVariables], [mixed $sqlBindTypes])

Starts the profile of a SQL sentence

public stopProfile ()

Stops the active profile

public getNumberTotalStatements ()

Returns the total number of SQL statements processed

public getTotalElapsedSeconds ()

Returns the total time in seconds spent by the profiles

public getProfiles ()

Returns all the processed profiles

public reset ()

Resets the profiler, cleaning up all the profiles

public getLastProfile ()

Returns the last profile executed in the profiler

Class Phalcon\Db\Profiler\Item

Source on GitHub

This class identifies each profile in a Phalcon\Db\Profiler

Methods

public setSqlStatement (mixed $sqlStatement)

SQL statement related to the profile

public getSqlStatement ()

SQL statement related to the profile

public setSqlVariables (array $sqlVariables)

SQL variables related to the profile

public getSqlVariables ()

SQL variables related to the profile

public setSqlBindTypes (array $sqlBindTypes)

SQL bind types related to the profile

public getSqlBindTypes ()

SQL bind types related to the profile

public setInitialTime (mixed $initialTime)

Timestamp when the profile started

public getInitialTime ()

Timestamp when the profile started

public setFinalTime (mixed $finalTime)

Timestamp when the profile ended

public getFinalTime ()

Timestamp when the profile ended

public getTotalElapsedSeconds ()

Returns the total time in seconds spent by the profile

Class Phalcon\Db\RawValue

Source on GitHub

This class allows to insert/update raw data without quoting or formatting. The next example shows how to use the MySQL now() function as a field value.

<?php

$subscriber = new Subscribers();
$subscriber->email = 'andres@phalconphp.com';
$subscriber->createdAt = new \Phalcon\Db\RawValue('now()');
$subscriber->save();
Methods

public getValue ()

Raw value without quoting or formatting

public __toString ()

Raw value without quoting or formatting

public __construct (mixed $value)

Phalcon\Db\RawValue constructor

Class Phalcon\Db\Reference

implements Phalcon\Db\ReferenceInterface

Source on GitHub

Allows to define reference constraints on tables

<?php

$reference = new \Phalcon\Db\Reference("field_fk", array(
    'referencedSchema' => "invoicing",
    'referencedTable' => "products",
    'columns' => array("product_type", "product_code"),
    'referencedColumns' => array("type", "code")
));
Methods

public getName ()

Constraint name

public getSchemaName ()

...

public getReferencedSchema ()

...

public getReferencedTable ()

Referenced Table

public getColumns ()

Local reference columns

public getReferencedColumns ()

Referenced Columns

public getOnDelete ()

ON DELETE

public getOnUpdate ()

ON UPDATE

public __construct (mixed $name, array $definition)

Phalcon\Db\Reference constructor

public static __set_state (array $data)

Restore a Phalcon\Db\Reference object from export

Class Phalcon\Db\Result\Pdo

implements Phalcon\Db\ResultInterface

Source on GitHub

Encapsulates the resultset internals

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_NUM);
while ($robot = $result->fetchArray()) {
    print_r($robot);
}
Methods

public __construct (Phalcon\Db\AdapterInterface $connection, PDOStatement $result, [string $sqlStatement], [array $bindParams], [array $bindTypes])

Phalcon\Db\Result\Pdo constructor

public execute ()

Allows to execute the statement again. Some database systems don’t support scrollable cursors, So, as cursors are forward only, we need to execute the cursor again to fetch rows from the begining

public fetch ([mixed $fetchStyle], [mixed $cursorOrientation], [mixed $cursorOffset])

Fetches an array/object of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_OBJ);
while ($robot = $result->fetch()) {
    echo $robot->name;
}

public fetchArray ()

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->setFetchMode(Phalcon\Db::FETCH_NUM);
while ($robot = result->fetchArray()) {
    print_r($robot);
}

public fetchAll ([mixed $fetchStyle], [mixed $fetchArgument], [mixed $ctorArgs])

Returns an array of arrays containing all the records in the result This method is affected by the active fetch flag set using Phalcon\Db\Result\Pdo::setFetchMode

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$robots = $result->fetchAll();

public numRows ()

Gets number of rows returned by a resultset

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
echo 'There are ', $result->numRows(), ' rows in the resultset';

public dataSeek (mixed $number)

Moves internal resultset cursor to another position letting us to fetch a certain row

<?php

$result = $connection->query("SELECT * FROM robots ORDER BY name");
$result->dataSeek(2); // Move to third row on result
$row = $result->fetch(); // Fetch third row

public setFetchMode (mixed $fetchMode, [mixed $colNoOrClassNameOrObject], [mixed $ctorargs])

Changes the fetching mode affecting Phalcon\Db\Result\Pdo::fetch()

<?php

//Return array with integer indexes
$result->setFetchMode(\Phalcon\Db::FETCH_NUM);

//Return associative array without integer indexes
$result->setFetchMode(\Phalcon\Db::FETCH_ASSOC);

//Return associative array together with integer indexes
$result->setFetchMode(\Phalcon\Db::FETCH_BOTH);

//Return an object
$result->setFetchMode(\Phalcon\Db::FETCH_OBJ);

public getInternalResult ()

Gets the internal PDO result object

Class Phalcon\Debug

Source on GitHub

Provides debug capabilities to Phalcon applications

Methods

public setUri (mixed $uri)

Change the base URI for static resources

public setShowBackTrace (mixed $showBackTrace)

Sets if files the exception’s backtrace must be showed

public setShowFiles (mixed $showFiles)

Set if files part of the backtrace must be shown in the output

public setShowFileFragment (mixed $showFileFragment)

Sets if files must be completely opened and showed in the output or just the fragment related to the exception

public listen ([mixed $exceptions], [mixed $lowSeverity])

Listen for uncaught exceptions and unsilent notices or warnings

public listenExceptions ()

Listen for uncaught exceptions

public listenLowSeverity ()

Listen for unsilent notices or warnings

public halt ()

Halts the request showing a backtrace

public debugVar (mixed $varz, [mixed $key])

Adds a variable to the debug output

public clearVars ()

Clears are variables added previously

protected _escapeString (mixed $value)

Escapes a string with htmlentities

protected _getArrayDump (array $argument, [mixed $n])

Produces a recursive representation of an array

protected _getVarDump (mixed $variable)

Produces an string representation of a variable

public getMajorVersion ()

Returns the major framework’s version

public getVersion ()

Generates a link to the current version documentation

public getCssSources ()

Returns the css sources

public getJsSources ()

Returns the javascript sources

final protected showTraceItem (mixed $n, array $trace)

Shows a backtrace item

public onUncaughtLowSeverity (mixed $severity, mixed $message, mixed $file, mixed $line, mixed $context)

Throws an exception when a notice or warning is raised

public onUncaughtException (Exception $exception)

Handles uncaught exceptions

Class Phalcon\Debug\Dump

Source on GitHub

Dumps information about a variable(s)

<?php

    $foo = 123;
    echo (new \Phalcon\Debug\Dump())->variable($foo, "foo");
<?php

    $foo = "string";
    $bar = ["key" => "value"];
    $baz = new stdClass();
    echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz);
Methods

public getDetailed ()

...

public setDetailed (mixed $detailed)

...

public __construct ([array $styles], [mixed $detailed])

Phalcon\Debug\Dump constructor

public all ()

Alias of variables() method

protected getStyle (mixed $type)

Get style for type

public setStyles ([mixed $styles])

Set styles for vars type

public one (mixed $variable, [mixed $name])

Alias of variable() method

protected output (mixed $variable, [mixed $name], [mixed $tab])

Prepare an HTML string of information about a single variable.

public variable (mixed $variable, [mixed $name])

Returns an HTML string of information about a single variable.

<?php

    echo (new \Phalcon\Debug\Dump())->variable($foo, "foo");

public variables ()

Returns an HTML string of debugging information about any number of variables, each wrapped in a “pre” tag.

<?php

    $foo = "string";
    $bar = ["key" => "value"];
    $baz = new stdClass();
    echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz);

public toJson (mixed $variable)

Returns an JSON string of information about a single variable.

<?php

    $foo = ["key" => "value"];
    echo (new \Phalcon\Debug\Dump())->toJson($foo);
    $foo = new stdClass();
    $foo->bar = 'buz';
    echo (new \Phalcon\Debug\Dump())->toJson($foo);
Class Phalcon\Debug\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Di

implements Phalcon\DiInterface, ArrayAccess

Source on GitHub

Phalcon\Di is a component that implements Dependency Injection/Service Location of services and it’s itself a container for them. Since Phalcon is highly decoupled, Phalcon\Di is essential to integrate the different components of the framework. The developer can also use this component to inject dependencies and manage global instances of the different classes used in the application. Basically, this component implements the Inversion of Control pattern. Applying this, the objects do not receive their dependencies using setters or constructors, but requesting a service dependency injector. This reduces the overall complexity, since there is only one way to get the required dependencies within a component. Additionally, this pattern increases testability in the code, thus making it less prone to errors.

<?php

 $di = new \Phalcon\Di();

 //Using a string definition
 $di->set("request", "Phalcon\Http\Request", true);

 //Using an anonymous function
 $di->set("request", function(){
  return new \Phalcon\Http\Request();
 }, true);

 $request = $di->getRequest();
Methods

public __construct ()

Phalcon\Di constructor

public setInternalEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the internal event manager

public getInternalEventsManager ()

Returns the internal event manager

public set (mixed $name, mixed $definition, [mixed $shared])

Registers a service in the services container

public setShared (mixed $name, mixed $definition)

Registers an “always shared” service in the services container

public remove (mixed $name)

Removes a service in the services container It also removes any shared instance created for the service

public attempt (mixed $name, mixed $definition, [mixed $shared])

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public setRaw (mixed $name, Phalcon\Di\ServiceInterface $rawDefinition)

Sets a service using a raw Phalcon\Di\Service definition

public getRaw (mixed $name)

Returns a service definition without resolving

public getService (mixed $name)

Returns a Phalcon\Di\Service instance

public get (mixed $name, [mixed $parameters])

Resolves the service based on its configuration

public mixed getShared (string $name, [array $parameters])

Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance

public has (mixed $name)

Check whether the DI contains a service by a name

public wasFreshInstance ()

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public getServices ()

Return the services registered in the DI

public offsetExists (mixed $name)

Check if a service is registered using the array syntax

public boolean offsetSet (string $name, mixed $definition)

Allows to register a shared service using the array syntax

<?php

$di["request"] = new \Phalcon\Http\Request();

public offsetGet (mixed $name)

Allows to obtain a shared service using the array syntax

<?php

var_dump($di["request"]);

public offsetUnset (mixed $name)

Removes a service from the services container using the array syntax

public __call (string $method, [array $arguments])

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector)

Set a default dependency injection container to be obtained into static methods

public static getDefault ()

Return the latest DI created

public static reset ()

Resets the internal default DI

Class Phalcon\Di\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Di\FactoryDefault

extends class Phalcon\Di

implements ArrayAccess, Phalcon\DiInterface

Source on GitHub

This is a variant of the standard Phalcon\Di. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually providing a full stack framework

Methods

public __construct ()

Phalcon\Di\FactoryDefault constructor

public setInternalEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di

Sets the internal event manager

public getInternalEventsManager () inherited from Phalcon\Di

Returns the internal event manager

public set (mixed $name, mixed $definition, [mixed $shared]) inherited from Phalcon\Di

Registers a service in the services container

public setShared (mixed $name, mixed $definition) inherited from Phalcon\Di

Registers an “always shared” service in the services container

public remove (mixed $name) inherited from Phalcon\Di

Removes a service in the services container It also removes any shared instance created for the service

public attempt (mixed $name, mixed $definition, [mixed $shared]) inherited from Phalcon\Di

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public setRaw (mixed $name, Phalcon\Di\ServiceInterface $rawDefinition) inherited from Phalcon\Di

Sets a service using a raw Phalcon\Di\Service definition

public getRaw (mixed $name) inherited from Phalcon\Di

Returns a service definition without resolving

public getService (mixed $name) inherited from Phalcon\Di

Returns a Phalcon\Di\Service instance

public get (mixed $name, [mixed $parameters]) inherited from Phalcon\Di

Resolves the service based on its configuration

public mixed getShared (string $name, [array $parameters]) inherited from Phalcon\Di

Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance

public has (mixed $name) inherited from Phalcon\Di

Check whether the DI contains a service by a name

public wasFreshInstance () inherited from Phalcon\Di

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public getServices () inherited from Phalcon\Di

Return the services registered in the DI

public offsetExists (mixed $name) inherited from Phalcon\Di

Check if a service is registered using the array syntax

public boolean offsetSet (string $name, mixed $definition) inherited from Phalcon\Di

Allows to register a shared service using the array syntax

<?php

$di["request"] = new \Phalcon\Http\Request();

public offsetGet (mixed $name) inherited from Phalcon\Di

Allows to obtain a shared service using the array syntax

<?php

var_dump($di["request"]);

public offsetUnset (mixed $name) inherited from Phalcon\Di

Removes a service from the services container using the array syntax

public __call (string $method, [array $arguments]) inherited from Phalcon\Di

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di

Set a default dependency injection container to be obtained into static methods

public static getDefault () inherited from Phalcon\Di

Return the latest DI created

public static reset () inherited from Phalcon\Di

Resets the internal default DI

Class Phalcon\Di\FactoryDefault\Cli

extends class Phalcon\Di\FactoryDefault

implements Phalcon\DiInterface, ArrayAccess

Source on GitHub

This is a variant of the standard Phalcon\Di. By default it automatically registers all the services provided by the framework. Thanks to this, the developer does not need to register each service individually. This class is specially suitable for CLI applications

Methods

public __construct ()

Phalcon\Di\FactoryDefault\Cli constructor

public setInternalEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di

Sets the internal event manager

public getInternalEventsManager () inherited from Phalcon\Di

Returns the internal event manager

public set (mixed $name, mixed $definition, [mixed $shared]) inherited from Phalcon\Di

Registers a service in the services container

public setShared (mixed $name, mixed $definition) inherited from Phalcon\Di

Registers an “always shared” service in the services container

public remove (mixed $name) inherited from Phalcon\Di

Removes a service in the services container It also removes any shared instance created for the service

public attempt (mixed $name, mixed $definition, [mixed $shared]) inherited from Phalcon\Di

Attempts to register a service in the services container Only is successful if a service hasn’t been registered previously with the same name

public setRaw (mixed $name, Phalcon\Di\ServiceInterface $rawDefinition) inherited from Phalcon\Di

Sets a service using a raw Phalcon\Di\Service definition

public getRaw (mixed $name) inherited from Phalcon\Di

Returns a service definition without resolving

public getService (mixed $name) inherited from Phalcon\Di

Returns a Phalcon\Di\Service instance

public get (mixed $name, [mixed $parameters]) inherited from Phalcon\Di

Resolves the service based on its configuration

public mixed getShared (string $name, [array $parameters]) inherited from Phalcon\Di

Resolves a service, the resolved service is stored in the DI, subsequent requests for this service will return the same instance

public has (mixed $name) inherited from Phalcon\Di

Check whether the DI contains a service by a name

public wasFreshInstance () inherited from Phalcon\Di

Check whether the last service obtained via getShared produced a fresh instance or an existing one

public getServices () inherited from Phalcon\Di

Return the services registered in the DI

public offsetExists (mixed $name) inherited from Phalcon\Di

Check if a service is registered using the array syntax

public boolean offsetSet (string $name, mixed $definition) inherited from Phalcon\Di

Allows to register a shared service using the array syntax

<?php

$di["request"] = new \Phalcon\Http\Request();

public offsetGet (mixed $name) inherited from Phalcon\Di

Allows to obtain a shared service using the array syntax

<?php

var_dump($di["request"]);

public offsetUnset (mixed $name) inherited from Phalcon\Di

Removes a service from the services container using the array syntax

public __call (string $method, [array $arguments]) inherited from Phalcon\Di

Magic method to get or set services using setters/getters

public static setDefault (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di

Set a default dependency injection container to be obtained into static methods

public static getDefault () inherited from Phalcon\Di

Return the latest DI created

public static reset () inherited from Phalcon\Di

Resets the internal default DI

Abstract class Phalcon\Di\Injectable

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This class allows to access services in the services container by just only accessing a public property with the same name of a registered service

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public getEventsManager ()

Returns the internal event manager

public __get (mixed $propertyName)

Magic method __get

Class Phalcon\Di\Service

implements Phalcon\Di\ServiceInterface

Source on GitHub

Represents individually a service in the services container

<?php

 $service = new \Phalcon\Di\Service('request', 'Phalcon\Http\Request');
 $request = service->resolve();
<?php
Methods

final public __construct (string $name, mixed $definition, [boolean $shared])

public getName ()

Returns the service’s name

public setShared (mixed $shared)

Sets if the service is shared or not

public isShared ()

Check whether the service is shared or not

public setSharedInstance (mixed $sharedInstance)

Sets/Resets the shared instance related to the service

public setDefinition (mixed $definition)

Set the service definition

public mixed getDefinition ()

Returns the service definition

public mixed resolve ([array $parameters], [Phalcon\DiInterface $dependencyInjector])

Resolves the service

public setParameter (mixed $position, array $parameter)

Changes a parameter in the definition without resolve the service

public array getParameter (int $position)

Returns a parameter in a specific position

public isResolved ()

Returns true if the service was resolved

public static __set_state (array $attributes)

Restore the internal state of a service

Class Phalcon\Di\Service\Builder

Source on GitHub

This class builds instances based on complex definitions

Methods

private mixed _buildParameter (Phalcon\DiInterface $dependencyInjector, int $position, array $argument)

Resolves a constructor/call parameter

private _buildParameters (Phalcon\DiInterface $dependencyInjector, array $arguments)

Resolves an array of parameters

public mixed build (Phalcon\DiInterface $dependencyInjector, array $definition, [array $parameters])

Builds a service using a complex service definition

Abstract class Phalcon\Dispatcher

implements Phalcon\DispatcherInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This is the base class for Phalcon\Mvc\Dispatcher and Phalcon\Cli\Dispatcher. This class can’t be instantiated directly, you can use it to create your own dispatchers.

Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public getEventsManager ()

Returns the internal event manager

public setActionSuffix (mixed $actionSuffix)

Sets the default action suffix

public getActionSuffix ()

Gets the default action suffix

public setModuleName (mixed $moduleName)

Sets the module where the controller is (only informative)

public getModuleName ()

Gets the module where the controller class is

public setNamespaceName (mixed $namespaceName)

Sets the namespace where the controller class is

public getNamespaceName ()

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (mixed $namespaceName)

Sets the default namespace

public getDefaultNamespace ()

Returns the default namespace

public setDefaultAction (mixed $actionName)

Sets the default action name

public setActionName (mixed $actionName)

Sets the action name to be dispatched

public getActionName ()

Gets the latest dispatched action name

public setParams (array $params)

Sets action params to be dispatched

public getParams ()

Gets action params

public setParam (mixed $param, mixed $value)

Set a param by its name or numeric index

public mixed getParam (mixed $param, [string | array $filters], [mixed $defaultValue])

Gets a param by its name or numeric index

public boolean hasParam (mixed $param)

Check if a param exists

public getActiveMethod ()

Returns the current method to be/executed in the dispatcher

public isFinished ()

Checks if the dispatch loop is finished or has more pendent controllers/tasks to dispatch

public setReturnedValue (mixed $value)

Sets the latest returned value by an action manually

public mixed getReturnedValue ()

Returns value returned by the latest dispatched action

public setModelBinding (boolean $value)

Enable/Disable model binding during dispatch

public object dispatch ()

Dispatches a handle action taking into account the routing parameters

protected object _dispatch ()

Dispatches a handle action taking into account the routing parameters

public forward (array $forward)

Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed

<?php

  $this->dispatcher->forward(array("controller" => "posts", "action" => "index"));

public wasForwarded ()

Check if the current executed action was forwarded by another one

public getHandlerClass ()

Possible class name that will be located to dispatch the request

public callActionMethod (mixed $handler, mixed $actionMethod, [array $params])

...

protected _resolveEmptyProperties ()

Set empty properties to their defaults (where defaults are available)

Class Phalcon\Escaper

implements Phalcon\EscaperInterface

Source on GitHub

Escapes different kinds of text securing them. By using this component you may prevent XSS attacks. This component only works with UTF-8. The PREG extension needs to be compiled with UTF-8 support.

<?php

$escaper = new \Phalcon\Escaper();
$escaped = $escaper->escapeCss("font-family: <Verdana>");
echo $escaped; // font\2D family\3A \20 \3C Verdana\3E
Methods

public setEncoding (mixed $encoding)

Sets the encoding to be used by the escaper

<?php

 $escaper->setEncoding('utf-8');

public getEncoding ()

Returns the internal encoding used by the escaper

public setHtmlQuoteType (mixed $quoteType)

Sets the HTML quoting type for htmlspecialchars

<?php

 $escaper->setHtmlQuoteType(ENT_XHTML);

public setDoubleEncode (mixed $doubleEncode)

Sets the double_encode to be used by the escaper

<?php

 $escaper->setDoubleEncode(false);

final public detectEncoding (mixed $str)

Detect the character encoding of a string to be handled by an encoder Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding()

final public normalizeEncoding (mixed $str)

Utility to normalize a string’s encoding to UTF-32.

public escapeHtml (mixed $text)

Escapes a HTML string. Internally uses htmlspecialchars

public escapeHtmlAttr (mixed $attribute)

Escapes a HTML attribute string

public escapeCss (mixed $css)

Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal escaped representation

public escapeJs (mixed $js)

Escape javascript strings by replacing non-alphanumeric chars by their hexadecimal escaped representation

public escapeUrl (mixed $url)

Escapes a URL. Internally uses rawurlencode

Class Phalcon\Escaper\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Events\Event

implements Phalcon\Events\EventInterface

Source on GitHub

This class offers contextual information of a fired event in the EventsManager

Methods

public getType ()

Event type

public getSource ()

Event source

public getData ()

Event data

public __construct (string $type, object $source, [mixed $data], [boolean $cancelable])

Phalcon\Events\Event constructor

public setData ([mixed $data])

Sets event data

public setType (mixed $type)

Sets event type

public stop ()

Stops the event preventing propagation

public isStopped ()

Check whether the event is currently stopped

public isCancelable ()

Check whether the event is cancelable

Class Phalcon\Events\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Events\Manager

implements Phalcon\Events\ManagerInterface

Source on GitHub

Phalcon Events Manager, offers an easy way to intercept and manipulate, if needed, the normal flow of operation. With the EventsManager the developer can create hooks or plugins that will offer monitoring of data, manipulation, conditional execution and much more.

Methods

public attach (string $eventType, object | callable $handler, [int $priority])

Attach a listener to the events manager

public detach (string $eventType, object $handler)

Detach the listener from the events manager

public enablePriorities (mixed $enablePriorities)

Set if priorities are enabled in the EventsManager

public arePrioritiesEnabled ()

Returns if priorities are enabled

public collectResponses (mixed $collect)

Tells the event manager if it needs to collect all the responses returned by every registered listener in a single fire

public isCollecting ()

Check if the events manager is collecting all all the responses returned by every registered listener in a single fire

public array getResponses ()

Returns all the responses returned by every handler executed by the last ‘fire’ executed

public detachAll ([mixed $type])

Removes all events from the EventsManager

final public mixed fireQueue (SplPriorityQueue | array $queue, Phalcon\Events\Event $event)

Internal handler to call a queue of events

public mixed fire (string $eventType, object $source, [mixed $data], [boolean $cancelable])

Fires an event in the events manager causing the active listeners to be notified about it

<?php

$eventsManager->fire('db', $connection);

public hasListeners (mixed $type)

Check whether certain type of event has listeners

public array getListeners (string $type)

Returns all the attached listeners of a certain type

Class Phalcon\Exception

extends class Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Filter

implements Phalcon\FilterInterface

Source on GitHub

The Phalcon\Filter component provides a set of commonly needed data filters. It provides object oriented wrappers to the php filter extension. Also allows the developer to define his/her own filters

<?php

$filter = new \Phalcon\Filter();
$filter->sanitize("some(one)@exa\\mple.com", "email"); // returns "someone@example.com"
$filter->sanitize("hello<<", "string"); // returns "hello"
$filter->sanitize("!100a019", "int"); // returns "100019"
$filter->sanitize("!100a019.01a", "float"); // returns "100019.01"
Constants

string FILTER_EMAIL

string FILTER_ABSINT

string FILTER_INT

string FILTER_INT_CAST

string FILTER_STRING

string FILTER_FLOAT

string FILTER_FLOAT_CAST

string FILTER_ALPHANUM

string FILTER_TRIM

string FILTER_STRIPTAGS

string FILTER_LOWER

string FILTER_UPPER

Methods

public add (mixed $name, mixed $handler)

Adds a user-defined filter

public sanitize (mixed $value, mixed $filters, [mixed $noRecursive])

Sanitizes a value with a specified single or set of filters

protected _sanitize (mixed $value, mixed $filter)

Internal sanitize wrapper to filter_var

public getFilters ()

Return the user-defined filters in the instance

Class Phalcon\Filter\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Flash

implements Phalcon\Di\InjectionAwareInterface

Source on GitHub

Shows HTML notifications related to different circumstances. Classes can be stylized using CSS

<?php

 $flash->success("The record was successfully deleted");
 $flash->error("Cannot open the file");
Methods

public __construct ([mixed $cssClasses])

Phalcon\Flash constructor

public getAutoescape ()

Returns the autoescape mode in generated html

public setAutoescape (mixed $autoescape)

Set the autoescape mode in generated html

public getEscaperService ()

Returns the Escaper Service

public setEscaperService (Phalcon\EscaperInterface $escaperService)

Sets the Escaper Service

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setImplicitFlush (mixed $implicitFlush)

Set whether the output must be implicitly flushed to the output or returned as string

public setAutomaticHtml (mixed $automaticHtml)

Set if the output must be implicitly formatted with HTML

public setCssClasses (array $cssClasses)

Set an array with CSS classes to format the messages

public error (mixed $message)

Shows a HTML error message

<?php

 $flash->error('This is an error');

public notice (mixed $message)

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public success (mixed $message)

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public warning (mixed $message)

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public string | void outputMessage (mixed $type, string | array $message)

Outputs a message formatting it with HTML

<?php

 $flash->outputMessage('error', message);

public clear ()

Clears accumulated messages when implicit flush is disabled

Class Phalcon\Flash\Direct

extends abstract class Phalcon\Flash

implements Phalcon\Di\InjectionAwareInterface, Phalcon\FlashInterface

Source on GitHub

This is a variant of the Phalcon\Flash that immediately outputs any message passed to it

Methods

public message (mixed $type, mixed $message)

Outputs a message

public output ([mixed $remove])

Prints the messages accumulated in the flasher

public __construct ([mixed $cssClasses]) inherited from Phalcon\Flash

Phalcon\Flash constructor

public getAutoescape () inherited from Phalcon\Flash

Returns the autoescape mode in generated html

public setAutoescape (mixed $autoescape) inherited from Phalcon\Flash

Set the autoescape mode in generated html

public getEscaperService () inherited from Phalcon\Flash

Returns the Escaper Service

public setEscaperService (Phalcon\EscaperInterface $escaperService) inherited from Phalcon\Flash

Sets the Escaper Service

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Flash

Sets the dependency injector

public getDI () inherited from Phalcon\Flash

Returns the internal dependency injector

public setImplicitFlush (mixed $implicitFlush) inherited from Phalcon\Flash

Set whether the output must be implicitly flushed to the output or returned as string

public setAutomaticHtml (mixed $automaticHtml) inherited from Phalcon\Flash

Set if the output must be implicitly formatted with HTML

public setCssClasses (array $cssClasses) inherited from Phalcon\Flash

Set an array with CSS classes to format the messages

public error (mixed $message) inherited from Phalcon\Flash

Shows a HTML error message

<?php

 $flash->error('This is an error');

public notice (mixed $message) inherited from Phalcon\Flash

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public success (mixed $message) inherited from Phalcon\Flash

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public warning (mixed $message) inherited from Phalcon\Flash

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public string | void outputMessage (mixed $type, string | array $message) inherited from Phalcon\Flash

Outputs a message formatting it with HTML

<?php

 $flash->outputMessage('error', message);

public clear () inherited from Phalcon\Flash

Clears accumulated messages when implicit flush is disabled

Class Phalcon\Flash\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Flash\Session

extends abstract class Phalcon\Flash

implements Phalcon\Di\InjectionAwareInterface, Phalcon\FlashInterface

Source on GitHub

Temporarily stores the messages in session, then messages can be printed in the next request

Methods

protected _getSessionMessages (mixed $remove, [mixed $type])

Returns the messages stored in session

protected _setSessionMessages (array $messages)

Stores the messages in session

public message (mixed $type, mixed $message)

Adds a message to the session flasher

public has ([mixed $type])

Checks whether there are messages

public getMessages ([mixed $type], [mixed $remove])

Returns the messages in the session flasher

public output ([mixed $remove])

Prints the messages in the session flasher

public clear ()

Clear messages in the session messenger

public __construct ([mixed $cssClasses]) inherited from Phalcon\Flash

Phalcon\Flash constructor

public getAutoescape () inherited from Phalcon\Flash

Returns the autoescape mode in generated html

public setAutoescape (mixed $autoescape) inherited from Phalcon\Flash

Set the autoescape mode in generated html

public getEscaperService () inherited from Phalcon\Flash

Returns the Escaper Service

public setEscaperService (Phalcon\EscaperInterface $escaperService) inherited from Phalcon\Flash

Sets the Escaper Service

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Flash

Sets the dependency injector

public getDI () inherited from Phalcon\Flash

Returns the internal dependency injector

public setImplicitFlush (mixed $implicitFlush) inherited from Phalcon\Flash

Set whether the output must be implicitly flushed to the output or returned as string

public setAutomaticHtml (mixed $automaticHtml) inherited from Phalcon\Flash

Set if the output must be implicitly formatted with HTML

public setCssClasses (array $cssClasses) inherited from Phalcon\Flash

Set an array with CSS classes to format the messages

public error (mixed $message) inherited from Phalcon\Flash

Shows a HTML error message

<?php

 $flash->error('This is an error');

public notice (mixed $message) inherited from Phalcon\Flash

Shows a HTML notice/information message

<?php

 $flash->notice('This is an information');

public success (mixed $message) inherited from Phalcon\Flash

Shows a HTML success message

<?php

 $flash->success('The process was finished successfully');

public warning (mixed $message) inherited from Phalcon\Flash

Shows a HTML warning message

<?php

 $flash->warning('Hey, this is important');

public string | void outputMessage (mixed $type, string | array $message) inherited from Phalcon\Flash

Outputs a message formatting it with HTML

<?php

 $flash->outputMessage('error', message);
Abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

This is a base class for form elements

Methods

public __construct (string $name, [array $attributes])

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form)

Sets the parent form to the element

public getForm ()

Returns the parent form to the element

public setName (mixed $name)

Sets the element name

public getName ()

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters)

Sets the element filters

public addFilter (mixed $filter)

Adds a filter to current list of filters

public mixed getFilters ()

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge])

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator)

Adds a validator to the element

public getValidators ()

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked])

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value)

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue])

Returns the value of an attribute if present

public setAttributes (array $attributes)

Sets default attributes for the element

public getAttributes ()

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value)

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue])

Returns the value of an option if present

public setUserOptions (array $options)

Sets options for the element

public getUserOptions ()

Returns the options for the element

public setLabel (mixed $label)

Sets the element label

public getLabel ()

Returns the element label

public label ([array $attributes])

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value)

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault ()

Returns the default value assigned to the element

public getValue ()

Returns the element value

public getMessages ()

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages ()

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group)

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message)

Appends a message to the internal message list

public clear ()

Clears every element in the form to its default value

public __toString ()

Magic method __toString renders the widget without attributes

abstract public render ([mixed $attributes]) inherited from Phalcon\Forms\ElementInterface

...

Class Phalcon\Forms\Element\Check

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=check] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Date

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=date] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Email

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=email] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\File

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=file] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Hidden

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=hidden] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Numeric

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=number] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Password

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=password] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Radio

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=radio] for forms

Methods

public render ([array $attributes])

Renders the element widget returning html

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Select

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component SELECT (choice) for forms

Methods

public __construct (string $name, [object | array $options], [array $attributes])

Phalcon\Forms\Element constructor

public Phalcon\Forms\Element setOptions (array | object $options)

Set the choice’s options

public array | object getOptions ()

Returns the choices’ options

public this addOption (array $option)

Adds an option to the current options

public render ([array $attributes])

Renders the element widget returning html

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Submit

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=submit] for forms

Methods

public render ([array $attributes])

Renders the element widget

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\Text

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component INPUT[type=text] for forms

Methods

public render ([array $attributes])

Renders the element widget

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Element\TextArea

extends abstract class Phalcon\Forms\Element

implements Phalcon\Forms\ElementInterface

Source on GitHub

Component TEXTAREA for forms

Methods

public render ([array $attributes])

Renders the element widget

public __construct (string $name, [array $attributes]) inherited from Phalcon\Forms\Element

Phalcon\Forms\Element constructor

public setForm (Phalcon\Forms\Form $form) inherited from Phalcon\Forms\Element

Sets the parent form to the element

public getForm () inherited from Phalcon\Forms\Element

Returns the parent form to the element

public setName (mixed $name) inherited from Phalcon\Forms\Element

Sets the element name

public getName () inherited from Phalcon\Forms\Element

Returns the element name

public Phalcon\Forms\ElementInterface setFilters (array | string $filters) inherited from Phalcon\Forms\Element

Sets the element filters

public addFilter (mixed $filter) inherited from Phalcon\Forms\Element

Adds a filter to current list of filters

public mixed getFilters () inherited from Phalcon\Forms\Element

Returns the element filters

public Phalcon\Forms\ElementInterface addValidators (array $validators, [mixed $merge]) inherited from Phalcon\Forms\Element

Adds a group of validators

public addValidator (Phalcon\Validation\ValidatorInterface $validator) inherited from Phalcon\Forms\Element

Adds a validator to the element

public getValidators () inherited from Phalcon\Forms\Element

Returns the validators registered for the element

public prepareAttributes ([array $attributes], [mixed $useChecked]) inherited from Phalcon\Forms\Element

Returns an array of prepared attributes for Phalcon\Tag helpers according to the element parameters

public Phalcon\Forms\ElementInterface setAttribute (string $attribute, mixed $value) inherited from Phalcon\Forms\Element

Sets a default attribute for the element

public mixed getAttribute (string $attribute, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an attribute if present

public setAttributes (array $attributes) inherited from Phalcon\Forms\Element

Sets default attributes for the element

public getAttributes () inherited from Phalcon\Forms\Element

Returns the default attributes for the element

public Phalcon\Forms\ElementInterface setUserOption (string $option, mixed $value) inherited from Phalcon\Forms\Element

Sets an option for the element

public mixed getUserOption (string $option, [mixed $defaultValue]) inherited from Phalcon\Forms\Element

Returns the value of an option if present

public setUserOptions (array $options) inherited from Phalcon\Forms\Element

Sets options for the element

public getUserOptions () inherited from Phalcon\Forms\Element

Returns the options for the element

public setLabel (mixed $label) inherited from Phalcon\Forms\Element

Sets the element label

public getLabel () inherited from Phalcon\Forms\Element

Returns the element label

public label ([array $attributes]) inherited from Phalcon\Forms\Element

Generate the HTML to label the element

public Phalcon\Forms\ElementInterface setDefault (mixed $value) inherited from Phalcon\Forms\Element

Sets a default value in case the form does not use an entity or there is no value available for the element in _POST

public getDefault () inherited from Phalcon\Forms\Element

Returns the default value assigned to the element

public getValue () inherited from Phalcon\Forms\Element

Returns the element value

public getMessages () inherited from Phalcon\Forms\Element

Returns the messages that belongs to the element The element needs to be attached to a form

public hasMessages () inherited from Phalcon\Forms\Element

Checks whether there are messages attached to the element

public setMessages (Phalcon\Validation\Message\Group $group) inherited from Phalcon\Forms\Element

Sets the validation messages related to the element

public appendMessage (Phalcon\Validation\MessageInterface $message) inherited from Phalcon\Forms\Element

Appends a message to the internal message list

public clear () inherited from Phalcon\Forms\Element

Clears every element in the form to its default value

public __toString () inherited from Phalcon\Forms\Element

Magic method __toString renders the widget without attributes

Class Phalcon\Forms\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Forms\Form

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Countable, Iterator, Traversable

Source on GitHub

This component allows to build forms using an object-oriented interface

Methods

public setValidation (mixed $validation)

...

public getValidation ()

...

public __construct ([object $entity], [array $userOptions])

Phalcon\Forms\Form constructor

public setAction (mixed $action)

Sets the form’s action

public getAction ()

Returns the form’s action

public setUserOption (string $option, mixed $value)

Sets an option for the form

public getUserOption (string $option, [mixed $defaultValue])

Returns the value of an option if present

public setUserOptions (array $options)

Sets options for the element

public getUserOptions ()

Returns the options for the element

public setEntity (object $entity)

Sets the entity related to the model

public object getEntity ()

Returns the entity related to the model

public getElements ()

Returns the form elements added to the form

public bind (array $data, object $entity, [array $whitelist])

Binds data to the entity

public isValid ([array $data], [object $entity])

Validates the form

public getMessages ([mixed $byItemName])

Returns the messages generated in the validation

public getMessagesFor (mixed $name)

Returns the messages generated for a specific element

public hasMessagesFor (mixed $name)

Check if messages were generated for a specific element

public add (Phalcon\Forms\ElementInterface $element, [mixed $position], [mixed $type])

Adds an element to the form

public render (string $name, [array $attributes])

Renders a specific item in the form

public get (mixed $name)

Returns an element added to the form by its name

public label (mixed $name, [array $attributes])

Generate the label of an element added to the form including HTML

public getLabel (mixed $name)

Returns a label for an element

public getValue (mixed $name)

Gets a value from the internal related entity or from the default value

public has (mixed $name)

Check if the form contains an element

public remove (mixed $name)

Removes an element from the form

public clear ([array $fields])

Clears every element in the form to its default value

public count ()

Returns the number of elements in the form

public rewind ()

Rewinds the internal iterator

public current ()

Returns the current element in the iterator

public key ()

Returns the current position/key in the iterator

public next ()

Moves the internal iteration pointer to the next position

public valid ()

Check if the current element in the iterator is valid

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Forms\Manager

Source on GitHub

Methods

public Phalcon\Forms\Form create ([string $name], [object $entity])

Creates a form registering it in the forms manager

public get (mixed $name)

Returns a form by its name

public has (mixed $name)

Checks if a form is registered in the forms manager

public set (mixed $name, Phalcon\Forms\Form $form)

Registers a form in the Forms Manager

Class Phalcon\Http\Request

implements Phalcon\Http\RequestInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Encapsulates request information for easy and secure access from application controllers. The request object is a simple value object that is passed between the dispatcher and controller classes. It packages the HTTP request environment.

<?php

 use Phalcon\Http\Request;

 $request = new Request();

 if ($request->isPost()) {
     if ($request->isAjax()) {
         echo 'Request was made using POST and AJAX';
     }
 }

 $request->getServer('HTTP_HOST'); // retrieve SERVER variables
 $request->getMethod();            // GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, PURGE, TRACE, CONNECT
 $request->getLanguages();         // an array of languages the client accepts
Methods

public getHttpMethodParameterOverride ()

...

public setHttpMethodParameterOverride (mixed $httpMethodParameterOverride)

...

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public get ([mixed $name], [mixed $filters], [mixed $defaultValue], [mixed $notAllowEmpty], [mixed $noRecursive])

Gets a variable from the $_REQUEST superglobal applying filters if needed. If no parameters are given the $_REQUEST superglobal is returned

<?php

//Returns value from $_REQUEST["user_email"] without sanitizing
$userEmail = $request->get("user_email");

//Returns value from $_REQUEST["user_email"] with sanitizing
$userEmail = $request->get("user_email", "email");

public getPost ([mixed $name], [mixed $filters], [mixed $defaultValue], [mixed $notAllowEmpty], [mixed $noRecursive])

Gets a variable from the $_POST superglobal applying filters if needed If no parameters are given the $_POST superglobal is returned

<?php

//Returns value from $_POST["user_email"] without sanitizing
$userEmail = $request->getPost("user_email");

//Returns value from $_POST["user_email"] with sanitizing
$userEmail = $request->getPost("user_email", "email");

public getPut ([mixed $name], [mixed $filters], [mixed $defaultValue], [mixed $notAllowEmpty], [mixed $noRecursive])

Gets a variable from put request

<?php

//Returns value from $_PUT["user_email"] without sanitizing
$userEmail = $request->getPut("user_email");

//Returns value from $_PUT["user_email"] with sanitizing
$userEmail = $request->getPut("user_email", "email");

public getQuery ([mixed $name], [mixed $filters], [mixed $defaultValue], [mixed $notAllowEmpty], [mixed $noRecursive])

Gets variable from $_GET superglobal applying filters if needed If no parameters are given the $_GET superglobal is returned

<?php

// Returns value from $_GET['id'] without sanitizing
$id = $request->getQuery('id');

// Returns value from $_GET['id'] with sanitizing
$id = $request->getQuery('id', 'int');

// Returns value from $_GET['id'] with a default value
$id = $request->getQuery('id', null, 150);

final protected getHelper (array $source, [mixed $name], [mixed $filters], [mixed $defaultValue], [mixed $notAllowEmpty], [mixed $noRecursive])

Helper to get data from superglobals, applying filters if needed. If no parameters are given the superglobal is returned.

public getServer (mixed $name)

Gets variable from $_SERVER superglobal

public has (mixed $name)

Checks whether $_REQUEST superglobal has certain index

public hasPost (mixed $name)

Checks whether $_POST superglobal has certain index

public hasPut (mixed $name)

Checks whether the PUT data has certain index

public hasQuery (mixed $name)

Checks whether $_GET superglobal has certain index

final public hasServer (mixed $name)

Checks whether $_SERVER superglobal has certain index

final public getHeader (mixed $header)

Gets HTTP header from request data

public getScheme ()

Gets HTTP schema (http/https)

public isAjax ()

Checks whether request has been made using ajax

public isSoap ()

Checks whether request has been made using SOAP

public isSoapRequested ()

Alias of isSoap(). It will be deprecated in future versions

public isSecure ()

Checks whether request has been made using any secure layer

public isSecureRequest ()

Alias of isSecure(). It will be deprecated in future versions

public getRawBody ()

Gets HTTP raw request body

public getJsonRawBody ([mixed $associative])

Gets decoded JSON HTTP raw request body

public getServerAddress ()

Gets active server address IP

public getServerName ()

Gets active server name

public getHttpHost ()

Gets host name used by the request. Request::getHttpHost trying to find host name in following order: - $_SERVER[‘HTTP_HOST’] - $_SERVER[‘SERVER_NAME’] - $_SERVER[‘SERVER_ADDR’] Optionally Request::getHttpHost validates and clean host name. The Request::$_strictHostCheck can be used to validate host name. Note: validation and cleaning have a negative performance impact because they use regular expressions.

<?php

 use Phalcon\Http\Request;

 $request = new Request;

 $_SERVER['HTTP_HOST'] = 'example.com';
 $request->getHttpHost(); // example.com

 $_SERVER['HTTP_HOST'] = 'example.com:8080';
 $request->getHttpHost(); // example.com:8080

 $request->setStrictHostCheck(true);
 $_SERVER['HTTP_HOST'] = 'ex=am~ple.com';
 $request->getHttpHost(); // UnexpectedValueException

 $_SERVER['HTTP_HOST'] = 'ExAmPlE.com';
 $request->getHttpHost(); // example.com

public setStrictHostCheck ([mixed $flag])

Sets if the Request::getHttpHost method must be use strict validation of host name or not

public isStrictHostCheck ()

Checks if the Request::getHttpHost method will be use strict validation of host name or not

public getPort ()

Gets information about the port on which the request is made.

final public getURI ()

Gets HTTP URI which request has been made

public getClientAddress ([mixed $trustForwardedHeader])

Gets most possible client IPv4 Address. This method search in _SERVER[‘REMOTE_ADDR’] and optionally in _SERVER[‘HTTP_X_FORWARDED_FOR’]

final public getMethod ()

Gets HTTP method which request has been made If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the “real” intended HTTP method. The _method request parameter can also be used to determine the HTTP method, but only if setHttpMethodParameterOverride(true) has been called. The method is always an uppercased string.

public getUserAgent ()

Gets HTTP user agent used to made the request

public isValidHttpMethod (mixed $method)

Checks if a method is a valid HTTP method

public isMethod (mixed $methods, [mixed $strict])

Check if HTTP method match any of the passed methods When strict is true it checks if validated methods are real HTTP methods

public isPost ()

Checks whether HTTP method is POST. if _SERVER[“REQUEST_METHOD”]===”POST”

public isGet ()

Checks whether HTTP method is GET. if _SERVER[“REQUEST_METHOD”]===”GET”

public isPut ()

Checks whether HTTP method is PUT. if _SERVER[“REQUEST_METHOD”]===”PUT”

public isPatch ()

Checks whether HTTP method is PATCH. if _SERVER[“REQUEST_METHOD”]===”PATCH”

public isHead ()

Checks whether HTTP method is HEAD. if _SERVER[“REQUEST_METHOD”]===”HEAD”

public isDelete ()

Checks whether HTTP method is DELETE. if _SERVER[“REQUEST_METHOD”]===”DELETE”

public isOptions ()

Checks whether HTTP method is OPTIONS. if _SERVER[“REQUEST_METHOD”]===”OPTIONS”

public isPurge ()

Checks whether HTTP method is PURGE (Squid and Varnish support). if _SERVER[“REQUEST_METHOD”]===”PURGE”

public isTrace ()

Checks whether HTTP method is TRACE. if _SERVER[“REQUEST_METHOD”]===”TRACE”

public isConnect ()

Checks whether HTTP method is CONNECT. if _SERVER[“REQUEST_METHOD”]===”CONNECT”

public hasFiles ([mixed $onlySuccessful])

Checks whether request include attached files

final protected hasFileHelper (mixed $data, mixed $onlySuccessful)

Recursively counts file in an array of files

public getUploadedFiles ([mixed $onlySuccessful])

Gets attached files as Phalcon\Http\Request\File instances

final protected smoothFiles (array $names, array $types, array $tmp_names, array $sizes, array $errors, mixed $prefix)

Smooth out $_FILES to have plain array with all files uploaded

public getHeaders ()

Returns the available headers in the request

public getHTTPReferer ()

Gets web page that refers active request. ie: http://www.google.com

final protected _getQualityHeader (mixed $serverIndex, mixed $name)

Process a request header and return an array of values with their qualities

final protected _getBestQuality (array $qualityParts, mixed $name)

Process a request header and return the one with best quality

public getContentType ()

Gets content type which request has been made

public getAcceptableContent ()

Gets an array with mime/types and their quality accepted by the browser/client from _SERVER[“HTTP_ACCEPT”]

public getBestAccept ()

Gets best mime/type accepted by the browser/client from _SERVER[“HTTP_ACCEPT”]

public getClientCharsets ()

Gets a charsets array and their quality accepted by the browser/client from _SERVER[“HTTP_ACCEPT_CHARSET”]

public getBestCharset ()

Gets best charset accepted by the browser/client from _SERVER[“HTTP_ACCEPT_CHARSET”]

public getLanguages ()

Gets languages array and their quality accepted by the browser/client from _SERVER[“HTTP_ACCEPT_LANGUAGE”]

public getBestLanguage ()

Gets best language accepted by the browser/client from _SERVER[“HTTP_ACCEPT_LANGUAGE”]

public getBasicAuth ()

Gets auth info accepted by the browser/client from $_SERVER[‘PHP_AUTH_USER’]

public getDigestAuth ()

Gets auth info accepted by the browser/client from $_SERVER[‘PHP_AUTH_DIGEST’]

Class Phalcon\Http\Request\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Http\Request\File

implements Phalcon\Http\Request\FileInterface

Source on GitHub

Provides OO wrappers to the $_FILES superglobal

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{

   public function uploadAction()
   {
      // Check if the user has uploaded files
      if ($this->request->hasFiles() == true) {
        // Print the real file names and their sizes
        foreach ($this->request->getUploadedFiles() as $file) {
            echo $file->getName(), " ", $file->getSize(), "\n";
        }
    }
   }
}
Methods

public getError ()

public getKey ()

public getExtension ()

public __construct (array $file, [mixed $key])

Phalcon\Http\Request\File constructor

public getSize ()

Returns the file size of the uploaded file

public getName ()

Returns the real name of the uploaded file

public getTempName ()

Returns the temporary name of the uploaded file

public getType ()

Returns the mime type reported by the browser This mime type is not completely secure, use getRealType() instead

public getRealType ()

Gets the real mime type of the upload file using finfo

public isUploadedFile ()

Checks whether the file has been uploaded via Post.

public moveTo (mixed $destination)

Moves the temporary file to a destination within the application

Class Phalcon\Http\Response

implements Phalcon\Http\ResponseInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Part of the HTTP cycle is return responses to the clients. Phalcon\HTTP\Response is the Phalcon component responsible to achieve this task. HTTP responses are usually composed by headers and body.

<?php

$response = new \Phalcon\Http\Response();
$response->setStatusCode(200, "OK");
$response->setContent("<html><body>Hello</body></html>");
$response->send();
Methods

public __construct ([mixed $content], [mixed $code], [mixed $status])

Phalcon\Http\Response constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setStatusCode (mixed $code, [mixed $message])

Sets the HTTP response code

<?php

$response->setStatusCode(404, "Not Found");

public getStatusCode ()

Returns the status code

<?php

print_r($response->getStatusCode());

public setHeaders (Phalcon\Http\Response\HeadersInterface $headers)

Sets a headers bag for the response externally

public getHeaders ()

Returns headers set by the user

public setCookies (Phalcon\Http\Response\CookiesInterface $cookies)

Sets a cookies bag for the response externally

public Phalcon\Http\Response\CookiesInterface getCookies ()

Returns coookies set by the user

public setHeader (mixed $name, mixed $value)

Overwrites a header in the response

<?php

$response->setHeader("Content-Type", "text/plain");

public setRawHeader (mixed $header)

Send a raw header to the response

<?php

$response->setRawHeader("HTTP/1.1 404 Not Found");

public resetHeaders ()

Resets all the stablished headers

public setExpires (DateTime $datetime)

Sets an Expires header in the response that allows to use the HTTP cache

<?php

$this->response->setExpires(new DateTime());

public setLastModified (DateTime $datetime)

Sets Last-Modified header

<?php

$this->response->setLastModified(new DateTime());

public setCache (mixed $minutes)

Sets Cache headers to use HTTP cache

<?php

$this->response->setCache(60);

public setNotModified ()

Sends a Not-Modified response

public setContentType (mixed $contentType, [mixed $charset])

Sets the response content-type mime, optionally the charset

<?php

$response->setContentType('application/pdf');
$response->setContentType('text/plain', 'UTF-8');

public setContentLength (mixed $contentLength)

Sets the response content-length

<?php

$response->setContentLength(2048);

public setEtag (mixed $etag)

Set a custom ETag

<?php

$response->setEtag(md5(time()));

public redirect ([mixed $location], [mixed $externalRedirect], [mixed $statusCode])

Redirect by HTTP to another action or URL

<?php

  //Using a string redirect (internal/external)
$response->redirect("posts/index");
$response->redirect("http://en.wikipedia.org", true);
$response->redirect("http://www.example.com/new-location", true, 301);

//Making a redirection based on a named route
$response->redirect(array(
    "for" => "index-lang",
    "lang" => "jp",
    "controller" => "index"
));

public setContent (mixed $content)

Sets HTTP response body

<?php

response->setContent("<h1>Hello!</h1>");

public setJsonContent (mixed $content, [mixed $jsonOptions], [mixed $depth])

Sets HTTP response body. The parameter is automatically converted to JSON and also sets default header: Content-Type: “application/json; charset=UTF-8”

<?php

$response->setJsonContent(array("status" => "OK"));

public appendContent (mixed $content)

Appends a string to the HTTP response body

public getContent ()

Gets the HTTP response body

public isSent ()

Check if the response is already sent

public sendHeaders ()

Sends headers to the client

public sendCookies ()

Sends cookies to the client

public send ()

Prints out HTTP response to the client

public setFileToSend (mixed $filePath, [mixed $attachmentName], [mixed $attachment])

Sets an attached file to be sent at the end of the request

Class Phalcon\Http\Response\Cookies

implements Phalcon\Http\Response\CookiesInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

This class is a bag to manage the cookies A cookies bag is automatically registered as part of the ‘response’ service in the DI

Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public useEncryption (mixed $useEncryption)

Set if cookies in the bag must be automatically encrypted/decrypted

public isUsingEncryption ()

Returns if the bag is automatically encrypting/decrypting cookies

public set (mixed $name, [mixed $value], [mixed $expire], [mixed $path], [mixed $secure], [mixed $domain], [mixed $httpOnly])

Sets a cookie to be sent at the end of the request This method overrides any cookie set before with the same name

public get (mixed $name)

Gets a cookie from the bag

public has (mixed $name)

Check if a cookie is defined in the bag or exists in the _COOKIE superglobal

public delete (mixed $name)

Deletes a cookie by its name This method does not removes cookies from the _COOKIE superglobal

public send ()

Sends the cookies to the client Cookies aren’t sent if headers are sent in the current request

public reset ()

Reset set cookies

Class Phalcon\Http\Response\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Http\Response\Headers

implements Phalcon\Http\Response\HeadersInterface

Source on GitHub

This class is a bag to manage the response headers

Methods

public set (mixed $name, mixed $value)

Sets a header to be sent at the end of the request

public get (mixed $name)

Gets a header value from the internal bag

public setRaw (mixed $header)

Sets a raw header to be sent at the end of the request

public remove (mixed $header)

Removes a header to be sent at the end of the request

public send ()

Sends the headers to the client

public reset ()

Reset set headers

public toArray ()

Returns the current headers as an array

public static __set_state (array $data)

Restore a \Phalcon\Http\Response\Headers object

Class Phalcon\Image

Source on GitHub

Constants

integer NONE

integer WIDTH

integer HEIGHT

integer AUTO

integer INVERSE

integer PRECISE

integer TENSILE

integer HORIZONTAL

integer VERTICAL

Abstract class Phalcon\Image\Adapter

Source on GitHub

All image adapters must use this class

Methods

public getImage ()

...

public getRealpath ()

...

public getWidth ()

Image width

public getHeight ()

Image height

public getType ()

Image type Driver dependent

public getMime ()

Image mime type

public resize ([mixed $width], [mixed $height], [mixed $master])

Resize the image to the given size

public liquidRescale (mixed $width, mixed $height, [mixed $deltaX], [mixed $rigidity])

This method scales the images using liquid rescaling method. Only support Imagick

public crop (mixed $width, mixed $height, [mixed $offsetX], [mixed $offsetY])

Crop an image to the given size

public rotate (mixed $degrees)

Rotate the image by a given amount

public flip (mixed $direction)

Flip the image along the horizontal or vertical axis

public sharpen (mixed $amount)

Sharpen the image by a given amount

public reflection (mixed $height, [mixed $opacity], [mixed $fadeIn])

Add a reflection to an image

public watermark (Phalcon\Image\Adapter $watermark, [mixed $offsetX], [mixed $offsetY], [mixed $opacity])

Add a watermark to an image with the specified opacity

public text (mixed $text, [mixed $offsetX], [mixed $offsetY], [mixed $opacity], [mixed $color], [mixed $size], [mixed $fontfile])

Add a text to an image with a specified opacity

public mask (Phalcon\Image\Adapter $watermark)

Composite one image onto another

public background (mixed $color, [mixed $opacity])

Set the background color of an image

public blur (mixed $radius)

Blur image

public pixelate (mixed $amount)

Pixelate image

public save ([mixed $file], [mixed $quality])

Save the image

public render ([mixed $ext], [mixed $quality])

Render the image and return the binary string

Class Phalcon\Image\Adapter\Gd

extends abstract class Phalcon\Image\Adapter

implements Phalcon\Image\AdapterInterface

Source on GitHub

Methods

public static check ()

...

public __construct (mixed $file, [mixed $width], [mixed $height])

...

protected _resize (mixed $width, mixed $height)

...

protected _crop (mixed $width, mixed $height, mixed $offsetX, mixed $offsetY)

...

protected _rotate (mixed $degrees)

...

protected _flip (mixed $direction)

...

protected _sharpen (mixed $amount)

...

protected _reflection (mixed $height, mixed $opacity, mixed $fadeIn)

...

protected _watermark (Phalcon\Image\Adapter $watermark, mixed $offsetX, mixed $offsetY, mixed $opacity)

...

protected _text (mixed $text, mixed $offsetX, mixed $offsetY, mixed $opacity, mixed $r, mixed $g, mixed $b, mixed $size, mixed $fontfile)

...

protected _mask (Phalcon\Image\Adapter $mask)

...

protected _background (mixed $r, mixed $g, mixed $b, mixed $opacity)

...

protected _blur (mixed $radius)

...

protected _pixelate (mixed $amount)

...

protected _save (mixed $file, mixed $quality)

...

protected _render (mixed $ext, mixed $quality)

...

protected _create (mixed $width, mixed $height)

...

public __destruct ()

...

public getImage () inherited from Phalcon\Image\Adapter

...

public getRealpath () inherited from Phalcon\Image\Adapter

...

public getWidth () inherited from Phalcon\Image\Adapter

Image width

public getHeight () inherited from Phalcon\Image\Adapter

Image height

public getType () inherited from Phalcon\Image\Adapter

Image type Driver dependent

public getMime () inherited from Phalcon\Image\Adapter

Image mime type

public resize ([mixed $width], [mixed $height], [mixed $master]) inherited from Phalcon\Image\Adapter

Resize the image to the given size

public liquidRescale (mixed $width, mixed $height, [mixed $deltaX], [mixed $rigidity]) inherited from Phalcon\Image\Adapter

This method scales the images using liquid rescaling method. Only support Imagick

public crop (mixed $width, mixed $height, [mixed $offsetX], [mixed $offsetY]) inherited from Phalcon\Image\Adapter

Crop an image to the given size

public rotate (mixed $degrees) inherited from Phalcon\Image\Adapter

Rotate the image by a given amount

public flip (mixed $direction) inherited from Phalcon\Image\Adapter

Flip the image along the horizontal or vertical axis

public sharpen (mixed $amount) inherited from Phalcon\Image\Adapter

Sharpen the image by a given amount

public reflection (mixed $height, [mixed $opacity], [mixed $fadeIn]) inherited from Phalcon\Image\Adapter

Add a reflection to an image

public watermark (Phalcon\Image\Adapter $watermark, [mixed $offsetX], [mixed $offsetY], [mixed $opacity]) inherited from Phalcon\Image\Adapter

Add a watermark to an image with the specified opacity

public text (mixed $text, [mixed $offsetX], [mixed $offsetY], [mixed $opacity], [mixed $color], [mixed $size], [mixed $fontfile]) inherited from Phalcon\Image\Adapter

Add a text to an image with a specified opacity

public mask (Phalcon\Image\Adapter $watermark) inherited from Phalcon\Image\Adapter

Composite one image onto another

public background (mixed $color, [mixed $opacity]) inherited from Phalcon\Image\Adapter

Set the background color of an image

public blur (mixed $radius) inherited from Phalcon\Image\Adapter

Blur image

public pixelate (mixed $amount) inherited from Phalcon\Image\Adapter

Pixelate image

public save ([mixed $file], [mixed $quality]) inherited from Phalcon\Image\Adapter

Save the image

public render ([mixed $ext], [mixed $quality]) inherited from Phalcon\Image\Adapter

Render the image and return the binary string

Class Phalcon\Image\Adapter\Imagick

extends abstract class Phalcon\Image\Adapter

implements Phalcon\Image\AdapterInterface

Source on GitHub

Image manipulation support. Allows images to be resized, cropped, etc.

<?php

 $image = new Phalcon\Image\Adapter\Imagick("upload/test.jpg");
 $image->resize(200, 200)->rotate(90)->crop(100, 100);
 if ($image->save()) {
     echo 'success';
 }
Methods

public static check ()

Checks if Imagick is enabled

public __construct (mixed $file, [mixed $width], [mixed $height])

\Phalcon\Image\Adapter\Imagick constructor

protected _resize (mixed $width, mixed $height)

Execute a resize.

protected _liquidRescale (mixed $width, mixed $height, mixed $deltaX, mixed $rigidity)

This method scales the images using liquid rescaling method. Only support Imagick

protected _crop (mixed $width, mixed $height, mixed $offsetX, mixed $offsetY)

Execute a crop.

protected _rotate (mixed $degrees)

Execute a rotation.

protected _flip (mixed $direction)

Execute a flip.

protected _sharpen (mixed $amount)

Execute a sharpen.

protected _reflection (mixed $height, mixed $opacity, mixed $fadeIn)

Execute a reflection.

protected _watermark (Phalcon\Image\Adapter $image, mixed $offsetX, mixed $offsetY, mixed $opacity)

Execute a watermarking.

protected _text (mixed $text, mixed $offsetX, mixed $offsetY, mixed $opacity, mixed $r, mixed $g, mixed $b, mixed $size, mixed $fontfile)

Execute a text

protected _mask (Phalcon\Image\Adapter $image)

Composite one image onto another

protected _background (mixed $r, mixed $g, mixed $b, mixed $opacity)

Execute a background.

protected _blur (mixed $radius)

Blur image

protected _pixelate (mixed $amount)

Pixelate image

protected _save (mixed $file, mixed $quality)

Execute a save.

protected _render (mixed $extension, mixed $quality)

Execute a render.

public __destruct ()

Destroys the loaded image to free up resources.

public getInternalImInstance ()

Get instance

public setResourceLimit (mixed $type, mixed $limit)

Sets the limit for a particular resource in megabytes

public getImage () inherited from Phalcon\Image\Adapter

...

public getRealpath () inherited from Phalcon\Image\Adapter

...

public getWidth () inherited from Phalcon\Image\Adapter

Image width

public getHeight () inherited from Phalcon\Image\Adapter

Image height

public getType () inherited from Phalcon\Image\Adapter

Image type Driver dependent

public getMime () inherited from Phalcon\Image\Adapter

Image mime type

public resize ([mixed $width], [mixed $height], [mixed $master]) inherited from Phalcon\Image\Adapter

Resize the image to the given size

public liquidRescale (mixed $width, mixed $height, [mixed $deltaX], [mixed $rigidity]) inherited from Phalcon\Image\Adapter

This method scales the images using liquid rescaling method. Only support Imagick

public crop (mixed $width, mixed $height, [mixed $offsetX], [mixed $offsetY]) inherited from Phalcon\Image\Adapter

Crop an image to the given size

public rotate (mixed $degrees) inherited from Phalcon\Image\Adapter

Rotate the image by a given amount

public flip (mixed $direction) inherited from Phalcon\Image\Adapter

Flip the image along the horizontal or vertical axis

public sharpen (mixed $amount) inherited from Phalcon\Image\Adapter

Sharpen the image by a given amount

public reflection (mixed $height, [mixed $opacity], [mixed $fadeIn]) inherited from Phalcon\Image\Adapter

Add a reflection to an image

public watermark (Phalcon\Image\Adapter $watermark, [mixed $offsetX], [mixed $offsetY], [mixed $opacity]) inherited from Phalcon\Image\Adapter

Add a watermark to an image with the specified opacity

public text (mixed $text, [mixed $offsetX], [mixed $offsetY], [mixed $opacity], [mixed $color], [mixed $size], [mixed $fontfile]) inherited from Phalcon\Image\Adapter

Add a text to an image with a specified opacity

public mask (Phalcon\Image\Adapter $watermark) inherited from Phalcon\Image\Adapter

Composite one image onto another

public background (mixed $color, [mixed $opacity]) inherited from Phalcon\Image\Adapter

Set the background color of an image

public blur (mixed $radius) inherited from Phalcon\Image\Adapter

Blur image

public pixelate (mixed $amount) inherited from Phalcon\Image\Adapter

Pixelate image

public save ([mixed $file], [mixed $quality]) inherited from Phalcon\Image\Adapter

Save the image

public render ([mixed $ext], [mixed $quality]) inherited from Phalcon\Image\Adapter

Render the image and return the binary string

Class Phalcon\Image\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Kernel

Source on GitHub

Methods

public static preComputeHashKey (mixed $key)

...

Class Phalcon\Loader

implements Phalcon\Events\EventsAwareInterface

Source on GitHub

This component helps to load your project classes automatically based on some conventions

<?php

 //Creates the autoloader
 $loader = new Loader();

 //Register some namespaces
 $loader->registerNamespaces(array(
   'Example\Base' => 'vendor/example/base/',
   'Example\Adapter' => 'vendor/example/adapter/',
   'Example' => 'vendor/example/'
 ));

 //register autoloader
 $loader->register();

 //Requiring this class will automatically include file vendor/example/adapter/Some.php
 $adapter = Example\Adapter\Some();
Methods

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public getEventsManager ()

Returns the internal event manager

public setExtensions (array $extensions)

Sets an array of file extensions that the loader must try in each attempt to locate the file

public getExtensions ()

Returns the file extensions registered in the loader

public registerNamespaces (array $namespaces, [mixed $merge])

Register namespaces and their related directories

protected prepareNamespace (array $namespace)

...

public getNamespaces ()

Returns the namespaces currently registered in the autoloader

public registerDirs (array $directories, [mixed $merge])

Register directories in which “not found” classes could be found

public getDirs ()

Returns the directories currently registered in the autoloader

public registerFiles (array $files, [mixed $merge])

Registers files that are “non-classes” hence need a “require”. This is very useful for including files that only have functions

public getFiles ()

Returns the files currently registered in the autoloader

public registerClasses (array $classes, [mixed $merge])

Register classes and their locations

public getClasses ()

Returns the class-map currently registered in the autoloader

public register ()

Register the autoload method

public unregister ()

Unregister the autoload method

public loadFiles ()

Checks if a file exists and then adds the file by doing virtual require

public autoLoad (mixed $className)

Autoloads the registered classes

public getFoundPath ()

Get the path when a class was found

public getCheckedPath ()

Get the path the loader is checking for a path

Class Phalcon\Loader\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Logger

Source on GitHub

Constants

integer SPECIAL

integer CUSTOM

integer DEBUG

integer INFO

integer NOTICE

integer WARNING

integer ERROR

integer ALERT

integer CRITICAL

integer EMERGENCE

integer EMERGENCY

Abstract class Phalcon\Logger\Adapter

Source on GitHub

Base class for Phalcon\Logger adapters

Methods

public setLogLevel (mixed $level)

Filters the logs sent to the handlers that are less or equal than a specific level

public getLogLevel ()

Returns the current log level

public setFormatter (Phalcon\Logger\FormatterInterface $formatter)

Sets the message formatter

public begin ()

Starts a transaction

public commit ()

Commits the internal transaction

public rollback ()

Rollbacks the internal transaction

public isTransaction ()

Returns the whether the logger is currently in an active transaction or not

public critical (mixed $message, [array $context])

Sends/Writes a critical message to the log

public emergency (mixed $message, [array $context])

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context])

Sends/Writes a debug message to the log

public error (mixed $message, [array $context])

Sends/Writes an error message to the log

public info (mixed $message, [array $context])

Sends/Writes an info message to the log

public notice (mixed $message, [array $context])

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context])

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context])

Sends/Writes an alert message to the log

public log (mixed $type, [mixed $message], [array $context])

Logs messages to the internal logger. Appends logs to the logger

Class Phalcon\Logger\Adapter\File

extends abstract class Phalcon\Logger\Adapter

implements Phalcon\Logger\AdapterInterface

Source on GitHub

Adapter to store logs in plain text files

<?php

$logger = new \Phalcon\Logger\Adapter\File("app/logs/test.log");
$logger->log("This is a message");
$logger->log(\Phalcon\Logger::ERROR, "This is an error");
$logger->error("This is another error");
$logger->close();
Methods

public getPath ()

File Path

public __construct (string $name, [array $options])

Phalcon\Logger\Adapter\File constructor

public getFormatter ()

Returns the internal formatter

public logInternal (mixed $message, mixed $type, mixed $time, array $context)

Writes the log to the file itself

public close ()

Closes the logger

public __wakeup ()

Opens the internal file handler after unserialization

public setLogLevel (mixed $level) inherited from Phalcon\Logger\Adapter

Filters the logs sent to the handlers that are less or equal than a specific level

public getLogLevel () inherited from Phalcon\Logger\Adapter

Returns the current log level

public setFormatter (Phalcon\Logger\FormatterInterface $formatter) inherited from Phalcon\Logger\Adapter

Sets the message formatter

public begin () inherited from Phalcon\Logger\Adapter

Starts a transaction

public commit () inherited from Phalcon\Logger\Adapter

Commits the internal transaction

public rollback () inherited from Phalcon\Logger\Adapter

Rollbacks the internal transaction

public isTransaction () inherited from Phalcon\Logger\Adapter

Returns the whether the logger is currently in an active transaction or not

public critical (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a critical message to the log

public emergency (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a debug message to the log

public error (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an error message to the log

public info (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an info message to the log

public notice (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an alert message to the log

public log (mixed $type, [mixed $message], [array $context]) inherited from Phalcon\Logger\Adapter

Logs messages to the internal logger. Appends logs to the logger

Class Phalcon\Logger\Adapter\Firephp

extends abstract class Phalcon\Logger\Adapter

implements Phalcon\Logger\AdapterInterface

Source on GitHub

Sends logs to FirePHP

<?php

 use Phalcon\Logger\Adapter\Firephp;
 use Phalcon\Logger;

 $logger = new Firephp();
 $logger->log(Logger::ERROR, 'This is an error');
 $logger->error('This is another error');
Methods

public getFormatter ()

Returns the internal formatter

public logInternal (mixed $message, mixed $type, mixed $time, array $context)

Writes the log to the stream itself

public close ()

Closes the logger

public setLogLevel (mixed $level) inherited from Phalcon\Logger\Adapter

Filters the logs sent to the handlers that are less or equal than a specific level

public getLogLevel () inherited from Phalcon\Logger\Adapter

Returns the current log level

public setFormatter (Phalcon\Logger\FormatterInterface $formatter) inherited from Phalcon\Logger\Adapter

Sets the message formatter

public begin () inherited from Phalcon\Logger\Adapter

Starts a transaction

public commit () inherited from Phalcon\Logger\Adapter

Commits the internal transaction

public rollback () inherited from Phalcon\Logger\Adapter

Rollbacks the internal transaction

public isTransaction () inherited from Phalcon\Logger\Adapter

Returns the whether the logger is currently in an active transaction or not

public critical (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a critical message to the log

public emergency (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a debug message to the log

public error (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an error message to the log

public info (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an info message to the log

public notice (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an alert message to the log

public log (mixed $type, [mixed $message], [array $context]) inherited from Phalcon\Logger\Adapter

Logs messages to the internal logger. Appends logs to the logger

Class Phalcon\Logger\Adapter\Stream

extends abstract class Phalcon\Logger\Adapter

implements Phalcon\Logger\AdapterInterface

Source on GitHub

Sends logs to a valid PHP stream

<?php

$logger = new \Phalcon\Logger\Adapter\Stream("php://stderr");
$logger->log("This is a message");
$logger->log(\Phalcon\Logger::ERROR, "This is an error");
$logger->error("This is another error");
Methods

public __construct (string $name, [array $options])

Phalcon\Logger\Adapter\Stream constructor

public getFormatter ()

Returns the internal formatter

public logInternal (mixed $message, mixed $type, mixed $time, array $context)

Writes the log to the stream itself

public close ()

Closes the logger

public setLogLevel (mixed $level) inherited from Phalcon\Logger\Adapter

Filters the logs sent to the handlers that are less or equal than a specific level

public getLogLevel () inherited from Phalcon\Logger\Adapter

Returns the current log level

public setFormatter (Phalcon\Logger\FormatterInterface $formatter) inherited from Phalcon\Logger\Adapter

Sets the message formatter

public begin () inherited from Phalcon\Logger\Adapter

Starts a transaction

public commit () inherited from Phalcon\Logger\Adapter

Commits the internal transaction

public rollback () inherited from Phalcon\Logger\Adapter

Rollbacks the internal transaction

public isTransaction () inherited from Phalcon\Logger\Adapter

Returns the whether the logger is currently in an active transaction or not

public critical (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a critical message to the log

public emergency (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a debug message to the log

public error (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an error message to the log

public info (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an info message to the log

public notice (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an alert message to the log

public log (mixed $type, [mixed $message], [array $context]) inherited from Phalcon\Logger\Adapter

Logs messages to the internal logger. Appends logs to the logger

Class Phalcon\Logger\Adapter\Syslog

extends abstract class Phalcon\Logger\Adapter

implements Phalcon\Logger\AdapterInterface

Source on GitHub

Sends logs to the system logger

<?php

$logger = new \Phalcon\Logger\Adapter\Syslog("ident", array(
    'option' => LOG_NDELAY,
    'facility' => LOG_MAIL
));
$logger->log("This is a message");
$logger->log(\Phalcon\Logger::ERROR, "This is an error");
$logger->error("This is another error");
Methods

public __construct (string $name, [array $options])

Phalcon\Logger\Adapter\Syslog constructor

public getFormatter ()

Returns the internal formatter

public logInternal (string $message, int $type, int $time, array $context)

Writes the log to the stream itself

public close ()

Closes the logger

public setLogLevel (mixed $level) inherited from Phalcon\Logger\Adapter

Filters the logs sent to the handlers that are less or equal than a specific level

public getLogLevel () inherited from Phalcon\Logger\Adapter

Returns the current log level

public setFormatter (Phalcon\Logger\FormatterInterface $formatter) inherited from Phalcon\Logger\Adapter

Sets the message formatter

public begin () inherited from Phalcon\Logger\Adapter

Starts a transaction

public commit () inherited from Phalcon\Logger\Adapter

Commits the internal transaction

public rollback () inherited from Phalcon\Logger\Adapter

Rollbacks the internal transaction

public isTransaction () inherited from Phalcon\Logger\Adapter

Returns the whether the logger is currently in an active transaction or not

public critical (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a critical message to the log

public emergency (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a debug message to the log

public error (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an error message to the log

public info (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an info message to the log

public notice (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context]) inherited from Phalcon\Logger\Adapter

Sends/Writes an alert message to the log

public log (mixed $type, [mixed $message], [array $context]) inherited from Phalcon\Logger\Adapter

Logs messages to the internal logger. Appends logs to the logger

Class Phalcon\Logger\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Logger\Formatter

implements Phalcon\Logger\FormatterInterface

Source on GitHub

This is a base class for logger formatters

Methods

public getTypeString (mixed $type)

Returns the string meaning of a logger constant

public interpolate (string $message, [array $context])

Interpolates context values into the message placeholders

abstract public format (mixed $message, mixed $type, mixed $timestamp, [mixed $context]) inherited from Phalcon\Logger\FormatterInterface

...

Class Phalcon\Logger\Formatter\Firephp

extends abstract class Phalcon\Logger\Formatter

implements Phalcon\Logger\FormatterInterface

Source on GitHub

Formats messages so that they can be sent to FirePHP

Methods

public getTypeString (mixed $type)

Returns the string meaning of a logger constant

public setShowBacktrace ([mixed $isShow])

Returns the string meaning of a logger constant

public getShowBacktrace ()

Returns the string meaning of a logger constant

public enableLabels ([mixed $isEnable])

Returns the string meaning of a logger constant

public labelsEnabled ()

Returns the labels enabled

public string format (string $message, int $type, int $timestamp, [array $context])

Applies a format to a message before sending it to the log

public interpolate (string $message, [array $context]) inherited from Phalcon\Logger\Formatter

Interpolates context values into the message placeholders

Class Phalcon\Logger\Formatter\Json

extends abstract class Phalcon\Logger\Formatter

implements Phalcon\Logger\FormatterInterface

Source on GitHub

Formats messages using JSON encoding

Methods

public string format (string $message, int $type, int $timestamp, [array $context])

Applies a format to a message before sent it to the internal log

public getTypeString (mixed $type) inherited from Phalcon\Logger\Formatter

Returns the string meaning of a logger constant

public interpolate (string $message, [array $context]) inherited from Phalcon\Logger\Formatter

Interpolates context values into the message placeholders

Class Phalcon\Logger\Formatter\Line

extends abstract class Phalcon\Logger\Formatter

implements Phalcon\Logger\FormatterInterface

Source on GitHub

Formats messages using an one-line string

Methods

public getDateFormat ()

Default date format

public setDateFormat (mixed $dateFormat)

Default date format

public getFormat ()

Format applied to each message

public setFormat (mixed $format)

Format applied to each message

public __construct ([string $format], [string $dateFormat])

Phalcon\Logger\Formatter\Line construct

public string format (string $message, int $type, int $timestamp, [array $context])

Applies a format to a message before sent it to the internal log

public getTypeString (mixed $type) inherited from Phalcon\Logger\Formatter

Returns the string meaning of a logger constant

public interpolate (string $message, [array $context]) inherited from Phalcon\Logger\Formatter

Interpolates context values into the message placeholders

Class Phalcon\Logger\Formatter\Syslog

extends abstract class Phalcon\Logger\Formatter

implements Phalcon\Logger\FormatterInterface

Source on GitHub

Prepares a message to be used in a Syslog backend

Methods

public array format (string $message, int $type, int $timestamp, [array $context])

Applies a format to a message before sent it to the internal log

public getTypeString (mixed $type) inherited from Phalcon\Logger\Formatter

Returns the string meaning of a logger constant

public interpolate (string $message, [array $context]) inherited from Phalcon\Logger\Formatter

Interpolates context values into the message placeholders

Class Phalcon\Logger\Item

Source on GitHub

Represents each item in a logging transaction

Methods

public getType ()

Log type

public getMessage ()

Log message

public getTime ()

Log timestamp

public getContext ()

...

public __construct (string $message, integer $type, [integer $time], [array $context])

Phalcon\Logger\Item constructor

Class Phalcon\Logger\Multiple

Source on GitHub

Handles multiples logger handlers

Methods

public getLoggers ()

...

public getFormatter ()

...

public getLogLevel ()

...

public push (Phalcon\Logger\AdapterInterface $logger)

Pushes a logger to the logger tail

public setFormatter (Phalcon\Logger\FormatterInterface $formatter)

Sets a global formatter

public setLogLevel (mixed $level)

Sets a global level

public log (mixed $type, [mixed $message], [array $context])

Sends a message to each registered logger

public critical (mixed $message, [array $context])

Sends/Writes an critical message to the log

public emergency (mixed $message, [array $context])

Sends/Writes an emergency message to the log

public debug (mixed $message, [array $context])

Sends/Writes a debug message to the log

public error (mixed $message, [array $context])

Sends/Writes an error message to the log

public info (mixed $message, [array $context])

Sends/Writes an info message to the log

public notice (mixed $message, [array $context])

Sends/Writes a notice message to the log

public warning (mixed $message, [array $context])

Sends/Writes a warning message to the log

public alert (mixed $message, [array $context])

Sends/Writes an alert message to the log

Class Phalcon\Mvc\Application

extends abstract class Phalcon\Application

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This component encapsulates all the complex operations behind instantiating every component needed and integrating it with the rest to allow the MVC pattern to operate as desired.

<?php

 use Phalcon\Mvc\Application;

 class MyApp extends Application
 {

    /**
     * Register the services here to make them general or register
     * in the ModuleDefinition to make them module-specific
     */
    protected function registerServices()
    {

    }

    /**
     * This method registers all the modules in the application
     */
    public function main()
    {
            $this->registerModules(array(
                    'frontend' => array(
                            'className' => 'Multiple\Frontend\Module',
                            'path' => '../apps/frontend/Module.php'
                    ),
                    'backend' => array(
                            'className' => 'Multiple\Backend\Module',
                            'path' => '../apps/backend/Module.php'
                    )
            ));
    }
}

$application = new MyApp();
$application->main();
Methods

public useImplicitView (mixed $implicitView)

By default. The view is implicitly buffering all the output You can full disable the view component using this method

public handle ([mixed $uri])

Handles a MVC request

public __construct ([Phalcon\DiInterface $dependencyInjector]) inherited from Phalcon\Application

Phalcon\Application

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Application

Sets the events manager

public getEventsManager () inherited from Phalcon\Application

Returns the internal event manager

public registerModules (array $modules, [mixed $merge]) inherited from Phalcon\Application

Register an array of modules present in the application

<?php

 $this->registerModules(
    [
            'frontend' => [
                    'className' => 'Multiple\Frontend\Module',
                    'path'      => '../apps/frontend/Module.php'
            ],
            'backend' => [
                    'className' => 'Multiple\Backend\Module',
                    'path'      => '../apps/backend/Module.php'
            ]
    ]
 );

public getModules () inherited from Phalcon\Application

Return the modules registered in the application

public getModule (mixed $name) inherited from Phalcon\Application

Gets the module definition registered in the application via module name

public setDefaultModule (mixed $defaultModule) inherited from Phalcon\Application

Sets the module name to be used if the router doesn’t return a valid module

public getDefaultModule () inherited from Phalcon\Application

Returns the default module name

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\Application\Exception

extends class Phalcon\Application\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Mvc\Collection

implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\CollectionInterface, Phalcon\Di\InjectionAwareInterface, Serializable

Source on GitHub

This component implements a high level abstraction for NoSQL databases which works with documents

Constants

integer OP_NONE

integer OP_CREATE

integer OP_UPDATE

integer OP_DELETE

Methods

final public __construct ([Phalcon\DiInterface $dependencyInjector], [Phalcon\Mvc\Collection\ManagerInterface $modelsManager])

Phalcon\Mvc\Collection constructor

public setId (mixed $id)

Sets a value for the _id property, creates a MongoId object if needed

public MongoId getId ()

Returns the value of the _id property

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public getDI ()

Returns the dependency injection container

protected setEventsManager (Phalcon\Mvc\Collection\ManagerInterface $eventsManager)

Sets a custom events manager

protected getEventsManager ()

Returns the custom events manager

public getCollectionManager ()

Returns the models manager related to the entity instance

public getReservedAttributes ()

Returns an array with reserved properties that cannot be part of the insert/update

protected useImplicitObjectIds (mixed $useImplicitObjectIds)

Sets if a model must use implicit objects ids

protected setSource (mixed $source)

Sets collection name which model should be mapped

public getSource ()

Returns collection name mapped in the model

public setConnectionService (mixed $connectionService)

Sets the DependencyInjection connection service name

public getConnectionService ()

Returns DependencyInjection connection service

public MongoDb getConnection ()

Retrieves a database connection

public mixed readAttribute (string $attribute)

Reads an attribute value by its name

<?php

echo $robot->readAttribute('name');

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

<?php

$robot->writeAttribute('name', 'Rosey');

public static cloneResult (Phalcon\Mvc\CollectionInterface $collection, array $document)

Returns a cloned collection

protected static array _getResultset (array $params, Phalcon\Mvc\Collection $collection, MongoDb $connection, boolean $unique)

Returns a collection resultset

protected static int _getGroupResultset (array $params, Phalcon\Mvc\Collection $collection, MongoDb $connection)

Perform a count over a resultset

final protected boolean _preSave (Phalcon\DiInterface $dependencyInjector, boolean $disableEvents, boolean $exists)

Executes internal hooks before save a document

final protected _postSave (mixed $disableEvents, mixed $success, mixed $exists)

Executes internal events after save a document

protected validate (Phalcon\Mvc\Model\ValidatorInterface $validator)

Executes validators on every validation call

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends \Phalcon\Mvc\Collection
{

public function validation()
{
    this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if (this->validationHasFailed() == true) {
            return false;
    }
}

}

public validationHasFailed ()

Check whether validation process has generated any messages

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends \Phalcon\Mvc\Collection
{

public function validation()
{
    this->validate(new ExclusionIn(array(
            'field' => 'status',
            'domain' => array('A', 'I')
    )));
    if (this->validationHasFailed() == true) {
            return false;
    }
}

}

public fireEvent (mixed $eventName)

Fires an internal event

public fireEventCancel (mixed $eventName)

Fires an internal event that cancels the operation

protected _cancelOperation (mixed $disableEvents)

Cancel the current operation

protected boolean _exists (MongoCollection $collection)

Checks if the document exists in the collection

public getMessages ()

Returns all the validation messages

<?php

 $robot = new Robots();
 $robot->type = 'mechanical';
 $robot->name = 'Astro Boy';
 $robot->year = 1952;
 if ($robot->save() == false) {
echo "Umh, We can't store robots right now ";
foreach ($robot->getMessages() as message) {
    echo message;
}
} else {
echo "Great, a new robot was saved successfully!";
}

public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

Appends a customized message on the validation process

<?php

use \Phalcon\Mvc\Model\Message as Message;

class Robots extends \Phalcon\Mvc\Model
{

    public function beforeSave()
    {
            if ($this->name == 'Peter') {
                    message = new Message("Sorry, but a robot cannot be named Peter");
                    $this->appendMessage(message);
            }
    }
}

protected prepareCU ()

Shared Code for CU Operations Prepares Collection

public save ()

Creates/Updates a collection based on the values in the attributes

public create ()

Creates a collection based on the values in the attributes

public createIfNotExist (array $criteria)

Creates a document based on the values in the attributes, if not found by criteria Preferred way to avoid duplication is to create index on attribute $robot = new Robot(); $robot->name = “MyRobot”; $robot->type = “Droid”; //create only if robot with same name and type does not exist $robot->createIfNotExist( array( “name”, “type” ) );

public update ()

Creates/Updates a collection based on the values in the attributes

public static findById (mixed $id)

Find a document by its id (_id)

<?php

 // Find user by using \MongoId object
 $user = Users::findById(new \MongoId('545eb081631d16153a293a66'));

 // Find user by using id as sting
 $user = Users::findById('45cbc4a0e4123f6920000002');

 // Validate input
 if ($user = Users::findById($_POST['id'])) {
     // ...
 }

public static findFirst ([array $parameters])

Allows to query the first record that match the specified conditions

<?php

 // What's the first robot in the robots table?
 $robot = Robots::findFirst();
 echo 'The robot name is ', $robot->name, "\n";

 // What's the first mechanical robot in robots table?
 $robot = Robots::findFirst([
     ['type' => 'mechanical']
 ]);
 echo 'The first mechanical robot name is ', $robot->name, "\n";

 // Get first virtual robot ordered by name
 $robot = Robots::findFirst([
     ['type' => 'mechanical'],
     'order' => ['name' => 1]
 ]);
 echo 'The first virtual robot name is ', $robot->name, "\n";

 // Get first robot by id (_id)
 $robot = Robots::findFirst([
     ['_id' => new \MongoId('45cbc4a0e4123f6920000002')]
 ]);
 echo 'The robot id is ', $robot->_id, "\n";

public static find ([array $parameters])

Allows to query a set of records that match the specified conditions

<?php

 //How many robots are there?
 $robots = Robots::find();
 echo "There are ", count($robots), "\n";

 //How many mechanical robots are there?
 $robots = Robots::find(array(
     array("type" => "mechanical")
 ));
 echo "There are ", count(robots), "\n";

 //Get and print virtual robots ordered by name
 $robots = Robots::findFirst(array(
     array("type" => "virtual"),
     "order" => array("name" => 1)
 ));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

 //Get first 100 virtual robots ordered by name
 $robots = Robots::find(array(
     array("type" => "virtual"),
     "order" => array("name" => 1),
     "limit" => 100
 ));
 foreach ($robots as $robot) {
   echo $robot->name, "\n";
 }

public static count ([array $parameters])

Perform a count over a collection

<?php

 echo 'There are ', Robots::count(), ' robots';

public static aggregate ([array $parameters])

Perform an aggregation using the Mongo aggregation framework

public static summatory (mixed $field, [mixed $conditions], [mixed $finalize])

Allows to perform a summatory group for a column in the collection

public delete ()

Deletes a model instance. Returning true on success or false otherwise.

<?php

$robot = Robots::findFirst();
$robot->delete();

foreach (Robots::find() as $robot) {
    $robot->delete();
}

protected addBehavior (Phalcon\Mvc\Collection\BehaviorInterface $behavior)

Sets up a behavior in a collection

public skipOperation (mixed $skip)

Skips the current operation forcing a success state

public toArray ()

Returns the instance as an array representation

<?php

 print_r($robot->toArray());

public serialize ()

Serializes the object ignoring connections or protected properties

public unserialize (mixed $data)

Unserializes the object from a serialized string

Abstract class Phalcon\Mvc\Collection\Behavior

Source on GitHub

This is an optional base class for ORM behaviors

Methods

public __construct ([array $options])

protected mustTakeAction (mixed $eventName)

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName])

Returns the behavior options related to an event

public notify (mixed $type, Phalcon\Mvc\CollectionInterface $model)

This method receives the notifications from the EventsManager

public missingMethod (Phalcon\Mvc\CollectionInterface $model, mixed $method, [mixed $arguments])

Acts as fallbacks when a missing method is called on the collection

Class Phalcon\Mvc\Collection\Behavior\SoftDelete

extends abstract class Phalcon\Mvc\Collection\Behavior

implements Phalcon\Mvc\Collection\BehaviorInterface

Source on GitHub

Instead of permanently delete a record it marks the record as deleted changing the value of a flag column

Methods

public notify (mixed $type, Phalcon\Mvc\CollectionInterface $model)

Listens for notifications from the models manager

public __construct ([array $options]) inherited from Phalcon\Mvc\Collection\Behavior

Phalcon\Mvc\Collection\Behavior

protected mustTakeAction (mixed $eventName) inherited from Phalcon\Mvc\Collection\Behavior

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName]) inherited from Phalcon\Mvc\Collection\Behavior

Returns the behavior options related to an event

public missingMethod (Phalcon\Mvc\CollectionInterface $model, mixed $method, [mixed $arguments]) inherited from Phalcon\Mvc\Collection\Behavior

Acts as fallbacks when a missing method is called on the collection

Class Phalcon\Mvc\Collection\Behavior\Timestampable

extends abstract class Phalcon\Mvc\Collection\Behavior

implements Phalcon\Mvc\Collection\BehaviorInterface

Source on GitHub

Allows to automatically update a model’s attribute saving the datetime when a record is created or updated

Methods

public notify (mixed $type, Phalcon\Mvc\CollectionInterface $model)

Listens for notifications from the models manager

public __construct ([array $options]) inherited from Phalcon\Mvc\Collection\Behavior

Phalcon\Mvc\Collection\Behavior

protected mustTakeAction (mixed $eventName) inherited from Phalcon\Mvc\Collection\Behavior

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName]) inherited from Phalcon\Mvc\Collection\Behavior

Returns the behavior options related to an event

public missingMethod (Phalcon\Mvc\CollectionInterface $model, mixed $method, [mixed $arguments]) inherited from Phalcon\Mvc\Collection\Behavior

Acts as fallbacks when a missing method is called on the collection

Class Phalcon\Mvc\Collection\Document

implements Phalcon\Mvc\EntityInterface, ArrayAccess

Source on GitHub

This component allows Phalcon\Mvc\Collection to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x].

Methods

public boolean offsetExists (int $index)

Checks whether an offset exists in the document

public offsetGet (mixed $index)

Returns the value of a field using the ArrayAccess interfase

public offsetSet (mixed $index, mixed $value)

Change a value using the ArrayAccess interface

public offsetUnset (string $offset)

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public mixed readAttribute (string $attribute)

Reads an attribute value by its name

<?php

  echo $robot->readAttribute('name');

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

<?php

  $robot->writeAttribute('name', 'Rosey');

public array toArray ()

Returns the instance as an array representation

Class Phalcon\Mvc\Collection\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Collection\Manager

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This components controls the initialization of models, keeping record of relations between the different models of the application. A CollectionManager is injected to a model via a Dependency Injector Container such as Phalcon\Di.

<?php

 $di = new \Phalcon\Di();

 $di->set('collectionManager', function(){
      return new \Phalcon\Mvc\Collection\Manager();
 });

 $robot = new Robots($di);
Methods

public getServiceName ()

...

public setServiceName (mixed $serviceName)

...

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the event manager

public getEventsManager ()

Returns the internal event manager

public setCustomEventsManager (Phalcon\Mvc\CollectionInterface $model, Phalcon\Events\ManagerInterface $eventsManager)

Sets a custom events manager for a specific model

public getCustomEventsManager (Phalcon\Mvc\CollectionInterface $model)

Returns a custom events manager related to a model

public initialize (Phalcon\Mvc\CollectionInterface $model)

Initializes a model in the models manager

public isInitialized (mixed $modelName)

Check whether a model is already initialized

public getLastInitialized ()

Get the latest initialized model

public setConnectionService (Phalcon\Mvc\CollectionInterface $model, mixed $connectionService)

Sets a connection service for a specific model

public getConnectionService (Phalcon\Mvc\CollectionInterface $model)

Gets a connection service for a specific model

public useImplicitObjectIds (Phalcon\Mvc\CollectionInterface $model, mixed $useImplicitObjectIds)

Sets whether a model must use implicit objects ids

public isUsingImplicitObjectIds (Phalcon\Mvc\CollectionInterface $model)

Checks if a model is using implicit object ids

public Mongo getConnection (Phalcon\Mvc\CollectionInterface $model)

Returns the connection related to a model

public notifyEvent (mixed $eventName, Phalcon\Mvc\CollectionInterface $model)

Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model

public missingMethod (Phalcon\Mvc\CollectionInterface $model, mixed $eventName, mixed $data)

Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that at least one was implemented

public addBehavior (Phalcon\Mvc\CollectionInterface $model, Phalcon\Mvc\Collection\BehaviorInterface $behavior)

Binds a behavior to a model

Abstract class Phalcon\Mvc\Controller

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ControllerInterface

Source on GitHub

Every application controller should extend this class that encapsulates all the controller functionality The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.

<?php

<?php

class PeopleController extends \Phalcon\Mvc\Controller
{

  //This action will be executed by default
  public function indexAction()
  {

  }

  public function findAction()
  {

  }

  public function saveAction()
  {
   //Forwards flow to the index action
   return $this->dispatcher->forward(array('controller' => 'people', 'action' => 'index'));
  }

}
Methods

final public __construct ()

Phalcon\Mvc\Controller constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\Dispatcher

extends abstract class Phalcon\Dispatcher

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\DispatcherInterface, Phalcon\Mvc\DispatcherInterface

Source on GitHub

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

$di = new \Phalcon\Di();

$dispatcher = new \Phalcon\Mvc\Dispatcher();

  $dispatcher->setDI($di);

$dispatcher->setControllerName('posts');
$dispatcher->setActionName('index');
$dispatcher->setParams(array());

$controller = $dispatcher->dispatch();
Constants

integer EXCEPTION_NO_DI

integer EXCEPTION_CYCLIC_ROUTING

integer EXCEPTION_HANDLER_NOT_FOUND

integer EXCEPTION_INVALID_HANDLER

integer EXCEPTION_INVALID_PARAMS

integer EXCEPTION_ACTION_NOT_FOUND

Methods

public setControllerSuffix (mixed $controllerSuffix)

Sets the default controller suffix

public setDefaultController (mixed $controllerName)

Sets the default controller name

public setControllerName (mixed $controllerName)

Sets the controller name to be dispatched

public getControllerName ()

Gets last dispatched controller name

public getPreviousNamespaceName ()

Gets previous dispatched namespace name

public getPreviousControllerName ()

Gets previous dispatched controller name

public getPreviousActionName ()

Gets previous dispatched action name

protected _throwDispatchException (mixed $message, [mixed $exceptionCode])

Throws an internal exception

protected _handleException (Exception $exception)

Handles a user exception

public getControllerClass ()

Possible controller class name that will be located to dispatch the request

public getLastController ()

Returns the latest dispatched controller

public getActiveController ()

Returns the active controller in the dispatcher

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Dispatcher

Sets the dependency injector

public getDI () inherited from Phalcon\Dispatcher

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Dispatcher

Sets the events manager

public getEventsManager () inherited from Phalcon\Dispatcher

Returns the internal event manager

public setActionSuffix (mixed $actionSuffix) inherited from Phalcon\Dispatcher

Sets the default action suffix

public getActionSuffix () inherited from Phalcon\Dispatcher

Gets the default action suffix

public setModuleName (mixed $moduleName) inherited from Phalcon\Dispatcher

Sets the module where the controller is (only informative)

public getModuleName () inherited from Phalcon\Dispatcher

Gets the module where the controller class is

public setNamespaceName (mixed $namespaceName) inherited from Phalcon\Dispatcher

Sets the namespace where the controller class is

public getNamespaceName () inherited from Phalcon\Dispatcher

Gets a namespace to be prepended to the current handler name

public setDefaultNamespace (mixed $namespaceName) inherited from Phalcon\Dispatcher

Sets the default namespace

public getDefaultNamespace () inherited from Phalcon\Dispatcher

Returns the default namespace

public setDefaultAction (mixed $actionName) inherited from Phalcon\Dispatcher

Sets the default action name

public setActionName (mixed $actionName) inherited from Phalcon\Dispatcher

Sets the action name to be dispatched

public getActionName () inherited from Phalcon\Dispatcher

Gets the latest dispatched action name

public setParams (array $params) inherited from Phalcon\Dispatcher

Sets action params to be dispatched

public getParams () inherited from Phalcon\Dispatcher

Gets action params

public setParam (mixed $param, mixed $value) inherited from Phalcon\Dispatcher

Set a param by its name or numeric index

public mixed getParam (mixed $param, [string | array $filters], [mixed $defaultValue]) inherited from Phalcon\Dispatcher

Gets a param by its name or numeric index

public boolean hasParam (mixed $param) inherited from Phalcon\Dispatcher

Check if a param exists

public getActiveMethod () inherited from Phalcon\Dispatcher

Returns the current method to be/executed in the dispatcher

public isFinished () inherited from Phalcon\Dispatcher

Checks if the dispatch loop is finished or has more pendent controllers/tasks to dispatch

public setReturnedValue (mixed $value) inherited from Phalcon\Dispatcher

Sets the latest returned value by an action manually

public mixed getReturnedValue () inherited from Phalcon\Dispatcher

Returns value returned by the latest dispatched action

public setModelBinding (boolean $value) inherited from Phalcon\Dispatcher

Enable/Disable model binding during dispatch

public object dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

protected object _dispatch () inherited from Phalcon\Dispatcher

Dispatches a handle action taking into account the routing parameters

public forward (array $forward) inherited from Phalcon\Dispatcher

Forwards the execution flow to another controller/action Dispatchers are unique per module. Forwarding between modules is not allowed

<?php

  $this->dispatcher->forward(array("controller" => "posts", "action" => "index"));

public wasForwarded () inherited from Phalcon\Dispatcher

Check if the current executed action was forwarded by another one

public getHandlerClass () inherited from Phalcon\Dispatcher

Possible class name that will be located to dispatch the request

public callActionMethod (mixed $handler, mixed $actionMethod, [array $params]) inherited from Phalcon\Dispatcher

...

protected _resolveEmptyProperties () inherited from Phalcon\Dispatcher

Set empty properties to their defaults (where defaults are available)

Class Phalcon\Mvc\Dispatcher\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Micro

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, ArrayAccess

Source on GitHub

With Phalcon you can create “Micro-Framework like” applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way.

<?php

 $app = new \Phalcon\Mvc\Micro();

 $app->get('/say/welcome/{name}', function ($name) {
    echo "<h1>Welcome $name!</h1>";
 });

 $app->handle();
Methods

public __construct ([Phalcon\DiInterface $dependencyInjector])

Phalcon\Mvc\Micro constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public Phalcon\Mvc\Router\RouteInterface map (string $routePattern, callable $handler)

Maps a route to a handler without any HTTP method constraint

public Phalcon\Mvc\Router\RouteInterface get (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is GET

public Phalcon\Mvc\Router\RouteInterface post (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is POST

public Phalcon\Mvc\Router\RouteInterface put (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is PUT

public Phalcon\Mvc\Router\RouteInterface patch (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is PATCH

public Phalcon\Mvc\Router\RouteInterface head (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is HEAD

public Phalcon\Mvc\Router\RouteInterface delete (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is DELETE

public Phalcon\Mvc\Router\RouteInterface options (string $routePattern, callable $handler)

Maps a route to a handler that only matches if the HTTP method is OPTIONS

public mount (Phalcon\Mvc\Micro\CollectionInterface $collection)

Mounts a collection of handlers

public Phalcon\Mvc\Micro notFound (callable $handler)

Sets a handler that will be called when the router doesn’t match any of the defined routes

public Phalcon\Mvc\Micro error (callable $handler)

Sets a handler that will be called when an exception is thrown handling the route

public getRouter ()

Returns the internal router used by the application

public Phalcon\Di\ServiceInterface setService (string $serviceName, mixed $definition, [boolean $shared])

Sets a service from the DI

public hasService (mixed $serviceName)

Checks if a service is registered in the DI

public object getService (string $serviceName)

Obtains a service from the DI

public mixed getSharedService (string $serviceName)

Obtains a shared service from the DI

public mixed handle ([string $uri])

Handle the whole request

public stop ()

Stops the middleware execution avoiding than other middlewares be executed

public setActiveHandler (callable $activeHandler)

Sets externally the handler that must be called by the matched route

public callable getActiveHandler ()

Return the handler that will be called for the matched route

public mixed getReturnedValue ()

Returns the value returned by the executed handler

public boolean offsetExists (string $alias)

Check if a service is registered in the internal services container using the array syntax

public offsetSet (string $alias, mixed $definition)

Allows to register a shared service in the internal services container using the array syntax

<?php

$app['request'] = new \Phalcon\Http\Request();

public mixed offsetGet (string $alias)

Allows to obtain a shared service in the internal services container using the array syntax

<?php

var_dump($di['request']);

public offsetUnset (string $alias)

Removes a service from the internal services container using the array syntax

public Phalcon\Mvc\Micro before (callable $handler)

Appends a before middleware to be called before execute the route

public Phalcon\Mvc\Micro after (callable $handler)

Appends an ‘after’ middleware to be called after execute the route

public Phalcon\Mvc\Micro finish (callable $handler)

Appends a ‘finish’ middleware to be called when the request is finished

public array getHandlers ()

Returns the internal handlers attached to the application

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\Micro\Collection

implements Phalcon\Mvc\Micro\CollectionInterface

Source on GitHub

Groups Micro-Mvc handlers as controllers

<?php

 $app = new \Phalcon\Mvc\Micro();

 $collection = new Collection();

 $collection->setHandler(new PostsController());

 $collection->get('/posts/edit/{id}', 'edit');

 $app->mount($collection);
Methods

protected _addMap (string | array $method, string $routePattern, mixed $handler, string $name)

Internal function to add a handler to the group

public setPrefix (mixed $prefix)

Sets a prefix for all routes added to the collection

public getPrefix ()

Returns the collection prefix if any

public array getHandlers ()

Returns the registered handlers

public Phalcon\Mvc\Micro\Collection setHandler (mixed $handler, [boolean $lazy])

Sets the main handler

public setLazy (mixed $lazy)

Sets if the main handler must be lazy loaded

public isLazy ()

Returns if the main handler must be lazy loaded

public mixed getHandler ()

Returns the main handler

public Phalcon\Mvc\Micro\Collection map (string $routePattern, callable $handler, [string $name])

Maps a route to a handler

public Phalcon\Mvc\Micro\Collection get (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is GET

public Phalcon\Mvc\Micro\Collection post (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is POST

public Phalcon\Mvc\Micro\Collection put (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is PUT

public Phalcon\Mvc\Micro\Collection patch (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is PATCH

public Phalcon\Mvc\Micro\Collection head (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is HEAD

public Phalcon\Mvc\Micro\Collection delete (string $routePattern, callable $handler, [string $name])

Maps a route to a handler that only matches if the HTTP method is DELETE

public Phalcon\Mvc\Micro\Collection options (string $routePattern, callable $handler, [mixed $name])

Maps a route to a handler that only matches if the HTTP method is OPTIONS

Class Phalcon\Mvc\Micro\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Micro\LazyLoader

Source on GitHub

Lazy-Load of handlers for Mvc\Micro using auto-loading

Methods

public getDefinition ()

...

public __construct (mixed $definition)

Phalcon\Mvc\Micro\LazyLoader constructor

public mixed __call (string $method, array $arguments)

Initializes the internal handler, calling functions on it

Abstract class Phalcon\Mvc\Model

implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\ModelInterface, Phalcon\Mvc\Model\ResultInterface, Phalcon\Di\InjectionAwareInterface, Serializable, JsonSerializable

Source on GitHub

Phalcon\Mvc\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM). A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models. Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use.

<?php

 $robot = new Robots();
 $robot->type = 'mechanical';
 $robot->name = 'Astro Boy';
 $robot->year = 1952;
 if ($robot->save() == false) {
  echo "Umh, We can store robots: ";
  foreach ($robot->getMessages() as $message) {
 echo message;
  }
 } else {
  echo "Great, a new robot was saved successfully!";
 }
Constants

integer OP_NONE

integer OP_CREATE

integer OP_UPDATE

integer OP_DELETE

integer DIRTY_STATE_PERSISTENT

integer DIRTY_STATE_TRANSIENT

integer DIRTY_STATE_DETACHED

Methods

final public __construct ([mixed $data], [Phalcon\DiInterface $dependencyInjector], [Phalcon\Mvc\Model\ManagerInterface $modelsManager])

Phalcon\Mvc\Model constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public getDI ()

Returns the dependency injection container

protected setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets a custom events manager

protected getEventsManager ()

Returns the custom events manager

public getModelsMetaData ()

Returns the models meta-data service related to the entity instance

public getModelsManager ()

Returns the models manager related to the entity instance

public setTransaction (Phalcon\Mvc\Model\TransactionInterface $transaction)

Sets a transaction related to the Model instance

<?php

use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;

try {

  $txManager = new TxManager();

  $transaction = $txManager->get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if ($robot->save() == false) {
  $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if ($robotPart->save() == false) {
  $transaction->rollback("Robot part cannot be saved");
  }

  $transaction->commit();

} catch (TxFailed $e) {
  echo 'Failed, reason: ', $e->getMessage();
}

protected setSource (mixed $source)

Sets table name which model should be mapped

public getSource ()

Returns table name mapped in the model

protected setSchema (mixed $schema)

Sets schema name where table mapped is located

public getSchema ()

Returns schema name where table mapped is located

public setConnectionService (mixed $connectionService)

Sets the DependencyInjection connection service name

public setReadConnectionService (mixed $connectionService)

Sets the DependencyInjection connection service name used to read data

public setWriteConnectionService (mixed $connectionService)

Sets the DependencyInjection connection service name used to write data

public getReadConnectionService ()

Returns the DependencyInjection connection service name used to read data related the model

public getWriteConnectionService ()

Returns the DependencyInjection connection service name used to write data related to the model

public setDirtyState (mixed $dirtyState)

Sets the dirty state of the object using one of the DIRTY_STATE_* constants

public getDirtyState ()

Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not

public getReadConnection ()

Gets the connection used to read data for the model

public getWriteConnection ()

Gets the connection used to write data to the model

public Phalcon\Mvc\Model assign (array $data, [mixed $dataColumnMap], [array $whiteList])

Assigns values to a model from an array

<?php

 $robot->assign(array(
'type' => 'mechanical',
'name' => 'Astro Boy',
'year' => 1952
 ));

 //assign by db row, column map needed
 $robot->assign($dbRow, array(
'db_type' => 'type',
'db_name' => 'name',
'db_year' => 'year'
 ));

 //allow assign only name and year
 $robot->assign($_POST, null, array('name', 'year');

public static cloneResultMap (Phalcon\Mvc\ModelInterface | Phalcon\Mvc\Model\Row $base, array $data, array $columnMap, [int $dirtyState], [boolean $keepSnapshots])

Assigns values to a model from an array returning a new model.

<?php

$robot = \Phalcon\Mvc\Model::cloneResultMap(new Robots(), array(
  'type' => 'mechanical',
  'name' => 'Astro Boy',
  'year' => 1952
));

public static mixed cloneResultMapHydrate (array $data, array $columnMap, int $hydrationMode)

Returns an hydrated result based on the data and the column map

public static Phalcon\Mvc\ModelInterface cloneResult (Phalcon\Mvc\ModelInterface $base, array $data, [int $dirtyState])

Assigns values to a model from an array returning a new model

<?php

$robot = Phalcon\Mvc\Model::cloneResult(new Robots(), array(
  'type' => 'mechanical',
  'name' => 'Astro Boy',
  'year' => 1952
));

public static find ([mixed $parameters])

Allows to query a set of records that match the specified conditions

<?php

 // How many robots are there?
 $robots = Robots::find();
 echo 'There are ', count($robots), "\n";

 // How many mechanical robots are there?
 $robots = Robots::find("type='mechanical'");
 echo 'There are ', count($robots), "\n";

 // Get and print virtual robots ordered by name
 $robots = Robots::find(["type='virtual'", 'order' => 'name']);
 foreach ($robots as $robot) {
 echo $robot->name, "\n";
 }

 // Get first 100 virtual robots ordered by name
 $robots = Robots::find(["type='virtual'", 'order' => 'name', 'limit' => 100]);
 foreach ($robots as $robot) {
 echo $robot->name, "\n";
 }

public static static findFirst ([string | array $parameters])

Allows to query the first record that match the specified conditions

<?php

 //What's the first robot in robots table?
 $robot = Robots::findFirst();
 echo "The robot name is ", $robot->name;

 //What's the first mechanical robot in robots table?
 $robot = Robots::findFirst("type='mechanical'");
 echo "The first mechanical robot name is ", $robot->name;

 //Get first virtual robot ordered by name
 $robot = Robots::findFirst(array("type='virtual'", "order" => "name"));
 echo "The first virtual robot name is ", $robot->name;

public static query ([Phalcon\DiInterface $dependencyInjector])

Create a criteria for a specific model

protected boolean _exists (Phalcon\Mvc\Model\MetaDataInterface $metaData, Phalcon\Db\AdapterInterface $connection, [string | array $table])

Checks if the current record already exists or not

protected static Phalcon\Mvc\Model\ResultsetInterface _groupResult (mixed $functionName, string $alias, array $parameters)

Generate a PHQL SELECT statement for an aggregate

public static mixed count ([array $parameters])

Allows to count how many records match the specified conditions

<?php

 //How many robots are there?
 $number = Robots::count();
 echo "There are ", $number, "\n";

 //How many mechanical robots are there?
 $number = Robots::count("type = 'mechanical'");
 echo "There are ", $number, " mechanical robots\n";

public static mixed sum ([array $parameters])

Allows to calculate a sum on a column that match the specified conditions

<?php

 //How much are all robots?
 $sum = Robots::sum(array('column' => 'price'));
 echo "The total price of robots is ", $sum, "\n";

 //How much are mechanical robots?
 $sum = Robots::sum(array("type = 'mechanical'", 'column' => 'price'));
 echo "The total price of mechanical robots is  ", $sum, "\n";

public static mixed maximum ([array $parameters])

Allows to get the maximum value of a column that match the specified conditions

<?php

 //What is the maximum robot id?
 $id = Robots::maximum(array('column' => 'id'));
 echo "The maximum robot id is: ", $id, "\n";

 //What is the maximum id of mechanical robots?
 $sum = Robots::maximum(array("type='mechanical'", 'column' => 'id'));
 echo "The maximum robot id of mechanical robots is ", $id, "\n";

public static mixed minimum ([array $parameters])

Allows to get the minimum value of a column that match the specified conditions

<?php

 //What is the minimum robot id?
 $id = Robots::minimum(array('column' => 'id'));
 echo "The minimum robot id is: ", $id;

 //What is the minimum id of mechanical robots?
 $sum = Robots::minimum(array("type='mechanical'", 'column' => 'id'));
 echo "The minimum robot id of mechanical robots is ", $id;

public static double average ([array $parameters])

Allows to calculate the average value on a column matching the specified conditions

<?php

 //What's the average price of robots?
 $average = Robots::average(array('column' => 'price'));
 echo "The average price is ", $average, "\n";

 //What's the average price of mechanical robots?
 $average = Robots::average(array("type='mechanical'", 'column' => 'price'));
 echo "The average price of mechanical robots is ", $average, "\n";

public fireEvent (mixed $eventName)

Fires an event, implicitly calls behaviors and listeners in the events manager are notified

public fireEventCancel (mixed $eventName)

Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns boolean false

protected _cancelOperation ()

Cancel the current operation

public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

Appends a customized message on the validation process

<?php

 use Phalcon\Mvc\Model;
 use Phalcon\Mvc\Model\Message as Message;

 class Robots extends Model
 {

   public function beforeSave()
   {
 if ($this->name == 'Peter') {
    $message = new Message("Sorry, but a robot cannot be named Peter");
    $this->appendMessage($message);
 }
   }
 }

protected validate (Phalcon\ValidationInterface $validator)

Executes validators on every validation call

<?php

use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\ExclusionIn;

class Subscriptors extends Model
{

public function validation()
  {
            $validator = new Validation();
            $validator->add('status', new ExclusionIn(array(
            'domain' => array('A', 'I')
    )));

    return $this->validate($validator);
}
}

public validationHasFailed ()

Check whether validation process has generated any messages

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionIn;

class Subscriptors extends Model
{

public function validation()
  {
  $validator = new Validation();

            $validator->validate('status', new ExclusionIn(array(
            'domain' => array('A', 'I')
    ));

    return $this->validate($validator);
}
}

public getMessages ([mixed $filter])

Returns array of validation messages

<?php

$robot = new Robots();
$robot->type = 'mechanical';
$robot->name = 'Astro Boy';
$robot->year = 1952;
if ($robot->save() == false) {
    echo "Umh, We can't store robots right now ";
    foreach ($robot->getMessages() as $message) {
            echo $message;
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

final protected _checkForeignKeysRestrict ()

Reads “belongs to” relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity

final protected _checkForeignKeysReverseCascade ()

Reads both “hasMany” and “hasOne” relations and checks the virtual foreign keys (cascade) when deleting records

final protected _checkForeignKeysReverseRestrict ()

Reads both “hasMany” and “hasOne” relations and checks the virtual foreign keys (restrict) when deleting records

protected _preSave (Phalcon\Mvc\Model\MetaDataInterface $metaData, mixed $exists, mixed $identityField)

Executes internal hooks before save a record

protected _postSave (mixed $success, mixed $exists)

Executes internal events after save a record

protected boolean _doLowInsert (Phalcon\Mvc\Model\MetaDataInterface $metaData, Phalcon\Db\AdapterInterface $connection, string | array $table, boolean | string $identityField)

Sends a pre-build INSERT SQL statement to the relational database system

protected boolean _doLowUpdate (Phalcon\Mvc\Model\MetaDataInterface $metaData, Phalcon\Db\AdapterInterface $connection, string | array $table)

Sends a pre-build UPDATE SQL statement to the relational database system

protected boolean _preSaveRelatedRecords (Phalcon\Db\AdapterInterface $connection, Phalcon\Mvc\ModelInterface[] $related)

Saves related records that must be stored prior to save the master record

protected boolean _postSaveRelatedRecords (Phalcon\Db\AdapterInterface $connection, Phalcon\Mvc\ModelInterface[] $related)

Save the related records assigned in the has-one/has-many relations

public boolean save ([array $data], [array $whiteList])

Inserts or updates a model instance. Returning true on success or false otherwise.

<?php

//Creating a new robot
$robot = new Robots();
$robot->type = 'mechanical';
$robot->name = 'Astro Boy';
$robot->year = 1952;
$robot->save();

//Updating a robot name
$robot = Robots::findFirst("id=100");
$robot->name = "Biomass";
$robot->save();

public create ([mixed $data], [mixed $whiteList])

Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise.

<?php

//Creating a new robot
$robot = new Robots();
$robot->type = 'mechanical';
$robot->name = 'Astro Boy';
$robot->year = 1952;
$robot->create();

  //Passing an array to create
  $robot = new Robots();
  $robot->create(array(
  'type' => 'mechanical',
  'name' => 'Astro Boy',
  'year' => 1952
  ));

public update ([mixed $data], [mixed $whiteList])

Updates a model instance. If the instance doesn’t exist in the persistence it will throw an exception Returning true on success or false otherwise.

<?php

//Updating a robot name
$robot = Robots::findFirst("id=100");
$robot->name = "Biomass";
$robot->update();

public delete ()

Deletes a model instance. Returning true on success or false otherwise.

<?php

$robot = Robots::findFirst("id=100");
$robot->delete();

foreach (Robots::find("type = 'mechanical'") as $robot) {
   $robot->delete();
}

public getOperationMade ()

Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants

public refresh ()

Refreshes the model attributes re-querying the record from the database

public skipOperation (mixed $skip)

Skips the current operation forcing a success state

public readAttribute (mixed $attribute)

Reads an attribute value by its name

<?php

 echo $robot->readAttribute('name');

public writeAttribute (mixed $attribute, mixed $value)

Writes an attribute value by its name

<?php

    $robot->writeAttribute('name', 'Rosey');

protected skipAttributes (array $attributes)

Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->skipAttributes(array('price'));
   }
}

protected skipAttributesOnCreate (array $attributes)

Sets a list of attributes that must be skipped from the generated INSERT statement

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->skipAttributesOnCreate(array('created_at'));
   }
}

protected skipAttributesOnUpdate (array $attributes)

Sets a list of attributes that must be skipped from the generated UPDATE statement

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->skipAttributesOnUpdate(array('modified_in'));
   }
}

protected allowEmptyStringValues (array $attributes)

Sets a list of attributes that must be skipped from the generated UPDATE statement

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->allowEmptyStringValues(array('name'));
   }
}

protected hasOne (mixed $fields, mixed $referenceModel, mixed $referencedFields, [mixed $options])

Setup a 1-1 relation between two models

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->hasOne('id', 'RobotsDescription', 'robots_id');
   }
}

protected belongsTo (mixed $fields, mixed $referenceModel, mixed $referencedFields, [mixed $options])

Setup a relation reverse 1-1 between two models

<?php

<?php

class RobotsParts extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->belongsTo('robots_id', 'Robots', 'id');
   }

}

protected hasMany (mixed $fields, mixed $referenceModel, mixed $referencedFields, [mixed $options])

Setup a relation 1-n between two models

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   $this->hasMany('id', 'RobotsParts', 'robots_id');
   }
}

protected Phalcon\Mvc\Model\Relation hasManyToMany (string | array $fields, string $intermediateModel, string | array $intermediateFields, string | array $intermediateReferencedFields, mixed $referenceModel, string | array $referencedFields, [array $options])

Setup a relation n-n between two models through an intermediate relation

<?php

<?php

class Robots extends \Phalcon\Mvc\Model
{

   public function initialize()
   {
   //Setup a many-to-many relation to Parts through RobotsParts
   $this->hasManyToMany(
            'id',
            'RobotsParts',
            'robots_id',
            'parts_id',
            'Parts',
            'id'
    );
   }
}

public addBehavior (Phalcon\Mvc\Model\BehaviorInterface $behavior)

Setups a behavior in a model

<?php

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;

class Robots extends Model
{

   public function initialize()
   {
    $this->addBehavior(new Timestampable(array(
            'onCreate' => array(
                    'field' => 'created_at',
                    'format' => 'Y-m-d'
            )
    )));
   }
}

protected keepSnapshots (mixed $keepSnapshot)

Sets if the model must keep the original record snapshot in memory

<?php

<?php
use Phalcon\Mvc\Model;

class Robots extends Model
{

   public function initialize()
   {
    $this->keepSnapshots(true);
   }
}

public setSnapshotData (array $data, [array $columnMap])

Sets the record’s snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data

public hasSnapshotData ()

Checks if the object has internal snapshot data

public getSnapshotData ()

Returns the internal snapshot data

public hasChanged ([string | array $fieldName])

Check if a specific attribute has changed This only works if the model is keeping data snapshots

public getChangedFields ()

Returns a list of changed values

protected useDynamicUpdate (mixed $dynamicUpdate)

Sets if a model must use dynamic update instead of the all-field update

<?php

<?php
use Phalcon\Mvc\Model;

class Robots extends Model
{

   public function initialize()
   {
    $this->useDynamicUpdate(true);
   }
}

public Phalcon\Mvc\Model\ResultsetInterface getRelated (string $alias, [array $arguments])

Returns related records based on defined relations

protected mixed _getRelatedRecords (string $modelName, string $method, array $arguments)

Returns related records defined relations depending on the method name

final protected static Phalcon\Mvc\ModelInterface[] | Phalcon\Mvc\ModelInterface | boolean _invokeFinder (string $method, array $arguments)

Try to check if the query must invoke a finder

public mixed __call (string $method, array $arguments)

Handles method calls when a method is not implemented

public static mixed __callStatic (string $method, array $arguments)

Handles method calls when a static method is not implemented

public __set (string $property, mixed $value)

Magic method to assign values to the the model

final protected string _possibleSetter (string $property, mixed $value)

Check for, and attempt to use, possible setter.

public Phalcon\Mvc\Model\Resultset | Phalcon\Mvc\Model __get (string $property)

Magic method to get related records using the relation alias as a property

public __isset (mixed $property)

Magic method to check if a property is a valid relation

public serialize ()

Serializes the object ignoring connections, services, related objects or static properties

public unserialize (mixed $data)

Unserializes the object from a serialized string

public dump ()

Returns a simple representation of the object that can be used with var_dump

<?php

 var_dump($robot->dump());

public array toArray ([array $columns])

Returns the instance as an array representation

<?php

 print_r($robot->toArray());

public array jsonSerialize ()

Serializes the object for json_encode

<?php

 echo json_encode($robot);

public static setup (array $options)

Enables/disables options in the ORM

public reset ()

Reset a model instance data

Abstract class Phalcon\Mvc\Model\Behavior

implements Phalcon\Mvc\Model\BehaviorInterface

Source on GitHub

This is an optional base class for ORM behaviors

Methods

public __construct ([array $options])

protected mustTakeAction (mixed $eventName)

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName])

Returns the behavior options related to an event

public notify (mixed $type, Phalcon\Mvc\ModelInterface $model)

This method receives the notifications from the EventsManager

public missingMethod (Phalcon\Mvc\ModelInterface $model, string $method, [array $arguments])

Acts as fallbacks when a missing method is called on the model

Class Phalcon\Mvc\Model\Behavior\SoftDelete

extends abstract class Phalcon\Mvc\Model\Behavior

implements Phalcon\Mvc\Model\BehaviorInterface

Source on GitHub

Instead of permanently delete a record it marks the record as deleted changing the value of a flag column

Methods

public notify (mixed $type, Phalcon\Mvc\ModelInterface $model)

Listens for notifications from the models manager

public __construct ([array $options]) inherited from Phalcon\Mvc\Model\Behavior

Phalcon\Mvc\Model\Behavior

protected mustTakeAction (mixed $eventName) inherited from Phalcon\Mvc\Model\Behavior

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName]) inherited from Phalcon\Mvc\Model\Behavior

Returns the behavior options related to an event

public missingMethod (Phalcon\Mvc\ModelInterface $model, string $method, [array $arguments]) inherited from Phalcon\Mvc\Model\Behavior

Acts as fallbacks when a missing method is called on the model

Class Phalcon\Mvc\Model\Behavior\Timestampable

extends abstract class Phalcon\Mvc\Model\Behavior

implements Phalcon\Mvc\Model\BehaviorInterface

Source on GitHub

Allows to automatically update a model’s attribute saving the datetime when a record is created or updated

Methods

public notify (mixed $type, Phalcon\Mvc\ModelInterface $model)

Listens for notifications from the models manager

public __construct ([array $options]) inherited from Phalcon\Mvc\Model\Behavior

Phalcon\Mvc\Model\Behavior

protected mustTakeAction (mixed $eventName) inherited from Phalcon\Mvc\Model\Behavior

Checks whether the behavior must take action on certain event

protected array getOptions ([string $eventName]) inherited from Phalcon\Mvc\Model\Behavior

Returns the behavior options related to an event

public missingMethod (Phalcon\Mvc\ModelInterface $model, string $method, [array $arguments]) inherited from Phalcon\Mvc\Model\Behavior

Acts as fallbacks when a missing method is called on the model

Class Phalcon\Mvc\Model\Criteria

implements Phalcon\Mvc\Model\CriteriaInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

This class is used to build the array parameter required by Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() using an object-oriented interface.

<?php

 $robots = Robots::query()
     ->where('type = :type:')
     ->andWhere('year < 2000')
     ->bind(['type' => 'mechanical'])
     ->limit(5, 10)
     ->orderBy('name')
     ->execute();
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public setModelName (mixed $modelName)

Set a model on which the query will be executed

public getModelName ()

Returns an internal model name on which the criteria will be applied

public bind (array $bindParams, [mixed $merge])

Sets the bound parameters in the criteria This method replaces all previously set bound parameters

public bindTypes (array $bindTypes)

Sets the bind types in the criteria This method replaces all previously set bound parameters

public distinct (mixed $distinct)

Sets SELECT DISTINCT / SELECT ALL flag

public Phalcon\Mvc\Model\Criteria columns (string | array $columns)

Sets the columns to be queried

<?php

$criteria->columns(array('id', 'name'));

public join (mixed $model, [mixed $conditions], [mixed $alias], [mixed $type])

Adds an INNER join to the query

<?php

$criteria->join('Robots');
$criteria->join('Robots', 'r.id = RobotsParts.robots_id');
$criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r');
$criteria->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT');

public innerJoin (mixed $model, [mixed $conditions], [mixed $alias])

Adds an INNER join to the query

<?php

$criteria->innerJoin('Robots');
$criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id');
$criteria->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public leftJoin (mixed $model, [mixed $conditions], [mixed $alias])

Adds a LEFT join to the query

<?php

$criteria->leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public rightJoin (mixed $model, [mixed $conditions], [mixed $alias])

Adds a RIGHT join to the query

<?php

$criteria->rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public where (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

Sets the conditions parameter in the criteria

public addWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

Appends a condition to the current conditions using an AND operator (deprecated)

public andWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

Appends a condition to the current conditions using an AND operator

public orWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

Appends a condition to the current conditions using an OR operator

public betweenWhere (mixed $expr, mixed $minimum, mixed $maximum)

Appends a BETWEEN condition to the current conditions

<?php

$criteria->betweenWhere('price', 100.25, 200.50);

public notBetweenWhere (mixed $expr, mixed $minimum, mixed $maximum)

Appends a NOT BETWEEN condition to the current conditions

<?php

$criteria->notBetweenWhere('price', 100.25, 200.50);

public inWhere (mixed $expr, array $values)

Appends an IN condition to the current conditions

<?php

     $criteria->inWhere('id', [1, 2, 3]);

public notInWhere (mixed $expr, array $values)

Appends a NOT IN condition to the current conditions

<?php

$criteria->notInWhere('id', [1, 2, 3]);

public conditions (mixed $conditions)

Adds the conditions parameter to the criteria

public order (mixed $orderColumns)

Adds the order-by parameter to the criteria (deprecated)

public orderBy (mixed $orderColumns)

Adds the order-by clause to the criteria

public groupBy (mixed $group)

Adds the group-by clause to the criteria

public having (mixed $having)

Adds the having clause to the criteria

public limit (mixed $limit, [mixed $offset])

Adds the limit parameter to the criteria

public forUpdate ([mixed $forUpdate])

Adds the “for_update” parameter to the criteria

public sharedLock ([mixed $sharedLock])

Adds the “shared_lock” parameter to the criteria

public cache (array $cache)

Sets the cache options in the criteria This method replaces all previously set cache options

public getWhere ()

Returns the conditions parameter in the criteria

public string | array | null getColumns ()

Returns the columns to be queried

public getConditions ()

Returns the conditions parameter in the criteria

public int | array | null getLimit ()

Returns the limit parameter in the criteria, which will be an integer if limit was set without an offset, an array with ‘number’ and ‘offset’ keys if an offset was set with the limit, or null if limit has not been set.

public getOrderBy ()

Returns the order clause in the criteria

public getGroupBy ()

Returns the group clause in the criteria

public getHaving ()

Returns the having clause in the criteria

public array getParams ()

Returns all the parameters defined in the criteria

public static fromInput (Phalcon\DiInterface $dependencyInjector, mixed $modelName, array $data, [mixed $operator])

Builds a Phalcon\Mvc\Model\Criteria based on an input array like _POST

public execute ()

Executes a find using the parameters built with the criteria

Class Phalcon\Mvc\Model\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Manager

implements Phalcon\Mvc\Model\ManagerInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

This components controls the initialization of models, keeping record of relations between the different models of the application. A ModelsManager is injected to a model via a Dependency Injector/Services Container such as Phalcon\Di.

<?php

 use Phalcon\Di;
 use Phalcon\Mvc\Model\Manager as ModelsManager;

 $di = new Di();

 $di->set('modelsManager', function() {
      return new ModelsManager();
 });

 $robot = new Robots($di);
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets a global events manager

public getEventsManager ()

Returns the internal event manager

public setCustomEventsManager (Phalcon\Mvc\ModelInterface $model, Phalcon\Events\ManagerInterface $eventsManager)

Sets a custom events manager for a specific model

public getCustomEventsManager (Phalcon\Mvc\ModelInterface $model)

Returns a custom events manager related to a model

public initialize (Phalcon\Mvc\ModelInterface $model)

Initializes a model in the model manager

public isInitialized (mixed $modelName)

Check whether a model is already initialized

public getLastInitialized ()

Get last initialized model

public load (mixed $modelName, [mixed $newInstance])

Loads a model throwing an exception if it doesn’t exist

public setModelSource (Phalcon\Mvc\ModelInterface $model, mixed $source)

Sets the mapped source for a model

final public isVisibleModelProperty (Phalcon\Mvc\ModelInterface $model, mixed $property)

Check whether a model property is declared as public.

<?php

 $isPublic = $manager->isVisibleModelProperty(new Robots(), 'name');

public getModelSource (Phalcon\Mvc\ModelInterface $model)

Returns the mapped source for a model

public setModelSchema (Phalcon\Mvc\ModelInterface $model, mixed $schema)

Sets the mapped schema for a model

public getModelSchema (Phalcon\Mvc\ModelInterface $model)

Returns the mapped schema for a model

public setConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

Sets both write and read connection service for a model

public setWriteConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

Sets write connection service for a model

public setReadConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

Sets read connection service for a model

public getReadConnection (Phalcon\Mvc\ModelInterface $model)

Returns the connection to read data related to a model

public getWriteConnection (Phalcon\Mvc\ModelInterface $model)

Returns the connection to write data related to a model

protected _getConnection (Phalcon\Mvc\ModelInterface $model, mixed $connectionServices)

Returns the connection to read or write data related to a model depending on the connection services.

public getReadConnectionService (Phalcon\Mvc\ModelInterface $model)

Returns the connection service name used to read data related to a model

public getWriteConnectionService (Phalcon\Mvc\ModelInterface $model)

Returns the connection service name used to write data related to a model

public _getConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionServices)

Returns the connection service name used to read or write data related to a model depending on the connection services

public notifyEvent (mixed $eventName, Phalcon\Mvc\ModelInterface $model)

Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model

public missingMethod (Phalcon\Mvc\ModelInterface $model, mixed $eventName, mixed $data)

Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented

public addBehavior (Phalcon\Mvc\ModelInterface $model, Phalcon\Mvc\Model\BehaviorInterface $behavior)

Binds a behavior to a model

public keepSnapshots (Phalcon\Mvc\ModelInterface $model, mixed $keepSnapshots)

Sets if a model must keep snapshots

public isKeepingSnapshots (Phalcon\Mvc\ModelInterface $model)

Checks if a model is keeping snapshots for the queried records

public useDynamicUpdate (Phalcon\Mvc\ModelInterface $model, mixed $dynamicUpdate)

Sets if a model must use dynamic update instead of the all-field update

public isUsingDynamicUpdate (Phalcon\Mvc\ModelInterface $model)

Checks if a model is using dynamic update instead of all-field update

public Phalcon\Mvc\Model\Relation addHasOne (Phalcon\Mvc\Model $model, mixed $fields, string $referencedModel, mixed $referencedFields, [array $options])

Setup a 1-1 relation between two models

public Phalcon\Mvc\Model\Relation addBelongsTo (Phalcon\Mvc\Model $model, mixed $fields, string $referencedModel, mixed $referencedFields, [array $options])

Setup a relation reverse many to one between two models

public addHasMany (Phalcon\Mvc\ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, [array $options])

Setup a relation 1-n between two models

public Phalcon\Mvc\Model\Relation addHasManyToMany (Phalcon\Mvc\ModelInterface $model, string $fields, string $intermediateModel, string $intermediateFields, string $intermediateReferencedFields, string $referencedModel, string $referencedFields, [array $options])

Setups a relation n-m between two models

public existsBelongsTo (mixed $modelName, mixed $modelRelation)

Checks whether a model has a belongsTo relation with another model

public existsHasMany (mixed $modelName, mixed $modelRelation)

Checks whether a model has a hasMany relation with another model

public existsHasOne (mixed $modelName, mixed $modelRelation)

Checks whether a model has a hasOne relation with another model

public existsHasManyToMany (mixed $modelName, mixed $modelRelation)

Checks whether a model has a hasManyToMany relation with another model

public getRelationByAlias (mixed $modelName, mixed $alias)

Returns a relation by its alias

final protected _mergeFindParameters (mixed $findParamsOne, mixed $findParamsTwo)

Merge two arrays of find parameters

public Phalcon\Mvc\Model\Resultset\Simple | Phalcon\Mvc\Model\Resultset\Simple | int | false getRelationRecords (Phalcon\Mvc\Model\RelationInterface $relation, mixed $method, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

Helper method to query records based on a relation definition

public getReusableRecords (mixed $modelName, mixed $key)

Returns a reusable object from the internal list

public setReusableRecords (mixed $modelName, mixed $key, mixed $records)

Stores a reusable record in the internal list

public clearReusableObjects ()

Clears the internal reusable list

public getBelongsToRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

Gets belongsTo related records from a model

public getHasManyRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

Gets hasMany related records from a model

public getHasOneRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

Gets belongsTo related records from a model

public getBelongsTo (Phalcon\Mvc\ModelInterface $model)

Gets all the belongsTo relations defined in a model

<?php

$relations = $modelsManager->getBelongsTo(new Robots());

public getHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasMany relations defined on a model

public getHasOne (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

public getHasManyToMany (Phalcon\Mvc\ModelInterface $model)

Gets hasManyToMany relations defined on a model

public getHasOneAndHasMany (Phalcon\Mvc\ModelInterface $model)

Gets hasOne relations defined on a model

public getRelations (mixed $modelName)

Query all the relationships defined on a model

public getRelationsBetween (mixed $first, mixed $second)

Query the first relationship defined between two models

public createQuery (mixed $phql)

Creates a Phalcon\Mvc\Model\Query without execute it

public executeQuery (mixed $phql, [mixed $placeholders], [mixed $types])

Creates a Phalcon\Mvc\Model\Query and execute it

public createBuilder ([mixed $params])

Creates a Phalcon\Mvc\Model\Query\Builder

public getLastQuery ()

Returns the last query created or executed in the models manager

public registerNamespaceAlias (mixed $alias, mixed $namespaceName)

Registers shorter aliases for namespaces in PHQL statements

public getNamespaceAlias (mixed $alias)

Returns a real namespace from its alias

public getNamespaceAliases ()

Returns all the registered namespace aliases

public __destruct ()

Destroys the current PHQL cache

Class Phalcon\Mvc\Model\Message

implements Phalcon\Mvc\Model\MessageInterface

Source on GitHub

Encapsulates validation info generated before save/delete records fails

<?php

use Phalcon\Mvc\Model\Message as Message;

  class Robots extends \Phalcon\Mvc\Model
  {

    public function beforeSave()
    {
      if ($this->name == 'Peter') {
        $text = "A robot cannot be named Peter";
        $field = "name";
        $type = "InvalidValue";
        $message = new Message($text, $field, $type);
        $this->appendMessage($message);
     }
   }

 }
Methods

public __construct (string $message, [string | array $field], [string $type], [Phalcon\Mvc\ModelInterface $model], [int | null $code])

Phalcon\Mvc\Model\Message constructor

public setType (mixed $type)

Sets message type

public getType ()

Returns message type

public setMessage (mixed $message)

Sets verbose message

public getMessage ()

Returns verbose message

public setField (mixed $field)

Sets field name related to message

public getField ()

Returns field name related to message

public setModel (Phalcon\Mvc\ModelInterface $model)

Set the model who generates the message

public setCode (mixed $code)

Sets code for the message

public getModel ()

Returns the model that produced the message

public getCode ()

Returns the message code

public __toString ()

Magic __toString method returns verbose message

public static __set_state (array $message)

Magic __set_state helps to re-build messages variable exporting

Abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\Model\MetaDataInterface

Source on GitHub

Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. this component collect them and store for further querying by Phalcon\Mvc\Model. Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data. A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:

<?php

$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(new Robots());
print_r($attributes);
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema)

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy)

Set the meta-data extraction strategy

public getStrategy ()

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model)

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index)

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data)

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model)

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index)

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model)

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model)

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model)

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model)

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model)

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model)

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model)

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model)

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute)

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty ()

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset ()

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();

abstract public read (mixed $key) inherited from Phalcon\Mvc\Model\MetaDataInterface

...

abstract public write (mixed $key, mixed $data) inherited from Phalcon\Mvc\Model\MetaDataInterface

...

Class Phalcon\Mvc\Model\MetaData\Apc

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in the APC cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apc_fetch(‘$PMM$’) or apc_fetch(‘$PMM$my-app-id’)

<?php

$metaData = new \Phalcon\Mvc\Model\Metadata\Apc(array(
    'prefix' => 'my-app-id',
    'lifetime' => 86400
));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Apc constructor

public read (mixed $key)

Reads meta-data from APC

public write (mixed $key, mixed $data)

Writes the meta-data to APC

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();
Class Phalcon\Mvc\Model\MetaData\Files

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in PHP files.

<?php

 $metaData = new \Phalcon\Mvc\Model\Metadata\Files(array(
    'metaDataDir' => 'app/cache/metadata/'
 ));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Files constructor

public mixed read (string $key)

Reads meta-data from files

public write (string $key, array $data)

Writes the meta-data to files

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();
Class Phalcon\Mvc\Model\MetaData\Libmemcached

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds)

<?php

$metaData = new Phalcon\Mvc\Model\Metadata\Libmemcached(array(
    'servers' => array(
         array('host' => 'localhost', 'port' => 11211, 'weight' => 1),
     ),
     'client' => array(
         Memcached::OPT_HASH => Memcached::HASH_MD5,
         Memcached::OPT_PREFIX_KEY => 'prefix.',
     ),
    'lifetime' => 3600,
    'prefix' => 'my_'
));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Libmemcached constructor

public read (mixed $key)

Reads metadata from Memcache

public write (mixed $key, mixed $data)

Writes the metadata to Memcache

public reset ()

Flush Memcache data and resets internal meta-data in order to regenerate it

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());
Class Phalcon\Mvc\Model\MetaData\Memcache

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds)

<?php

$metaData = new Phalcon\Mvc\Model\Metadata\Memcache(array(
    'prefix' => 'my-app-id',
    'lifetime' => 86400,
    'host' => 'localhost',
    'port' => 11211,
    'persistent' => false
));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Memcache constructor

public read (mixed $key)

Reads metadata from Memcache

public write (mixed $key, mixed $data)

Writes the metadata to Memcache

public reset ()

Flush Memcache data and resets internal meta-data in order to regenerate it

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());
Class Phalcon\Mvc\Model\MetaData\Memory

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in memory. Data will be erased when the request finishes

Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Memory constructor

public array read (string $key)

Reads the meta-data from temporal memory

public write (string $key, array $data)

Writes the meta-data to temporal memory

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();
Class Phalcon\Mvc\Model\MetaData\Redis

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds)

<?php

 use Phalcon\Mvc\Model\Metadata\Redis;

 $metaData = new Redis([
     'host'       => '127.0.0.1',
     'port'       => 6379,
     'persistent' => 0,
     'statsKey'   => '_PHCM_MM',
     'lifetime'   => 172800,
     'index'      => 2,
 ]);
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Redis constructor

public read (mixed $key)

Reads metadata from Redis

public write (mixed $key, mixed $data)

Writes the metadata to Redis

public reset ()

Flush Redis data and resets internal meta-data in order to regenerate it

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());
Class Phalcon\Mvc\Model\MetaData\Session

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in session. Data will erased when the session finishes. Meta-data are permanent while the session is active. You can query the meta-data by printing $_SESSION[‘$PMM$’]

<?php

 $metaData = new \Phalcon\Mvc\Model\Metadata\Session(array(
    'prefix' => 'my-app-id'
 ));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Session constructor

public array read (string $key)

Reads meta-data from $_SESSION

public write (string $key, array $data)

Writes the meta-data to $_SESSION

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();
Class Phalcon\Mvc\Model\MetaData\Strategy\Annotations

implements Phalcon\Mvc\Model\MetaData\StrategyInterface

Source on GitHub

Methods

final public getMetaData (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

The meta-data is obtained by reading the column descriptions from the database information schema

final public getColumnMaps (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

Read the model’s column map, this can’t be inferred

Class Phalcon\Mvc\Model\MetaData\Strategy\Introspection

implements Phalcon\Mvc\Model\MetaData\StrategyInterface

Source on GitHub

Queries the table meta-data in order to introspect the model’s metadata

Methods

final public getMetaData (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

The meta-data is obtained by reading the column descriptions from the database information schema

final public getColumnMaps (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

Read the model’s column map, this can’t be inferred

Class Phalcon\Mvc\Model\MetaData\Xcache

extends abstract class Phalcon\Mvc\Model\MetaData

implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Stores model meta-data in the XCache cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing xcache_get(‘$PMM$’) or xcache_get(‘$PMM$my-app-id’)

<?php

$metaData = new Phalcon\Mvc\Model\Metadata\Xcache(array(
    'prefix' => 'my-app-id',
    'lifetime' => 86400
));
Constants

integer MODELS_ATTRIBUTES

integer MODELS_PRIMARY_KEY

integer MODELS_NON_PRIMARY_KEY

integer MODELS_NOT_NULL

integer MODELS_DATA_TYPES

integer MODELS_DATA_TYPES_NUMERIC

integer MODELS_DATE_AT

integer MODELS_DATE_IN

integer MODELS_IDENTITY_COLUMN

integer MODELS_DATA_TYPES_BIND

integer MODELS_AUTOMATIC_DEFAULT_INSERT

integer MODELS_AUTOMATIC_DEFAULT_UPDATE

integer MODELS_DEFAULT_VALUES

integer MODELS_EMPTY_STRING_VALUES

integer MODELS_COLUMN_MAP

integer MODELS_REVERSE_COLUMN_MAP

Methods

public __construct ([array $options])

Phalcon\Mvc\Model\MetaData\Xcache constructor

public array read (string $key)

Reads metadata from XCache

public write (string $key, array $data)

Writes the metadata to XCache

final protected _initialize (Phalcon\Mvc\ModelInterface $model, mixed $key, mixed $table, mixed $schema) inherited from Phalcon\Mvc\Model\MetaData

Initialize the metadata for certain table

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Model\MetaData

Sets the DependencyInjector container

public getDI () inherited from Phalcon\Mvc\Model\MetaData

Returns the DependencyInjector container

public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy) inherited from Phalcon\Mvc\Model\MetaData

Set the meta-data extraction strategy

public getStrategy () inherited from Phalcon\Mvc\Model\MetaData

Return the strategy to obtain the meta-data

final public readMetaData (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the complete meta-data for certain model

<?php

print_r($metaData->readMetaData(new Robots());

final public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads meta-data for certain model

<?php

print_r($metaData->readMetaDataIndex(new Robots(), 0);

final public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data) inherited from Phalcon\Mvc\Model\MetaData

Writes meta-data for certain model using a MODEL_* constant

<?php

print_r($metaData->writeColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP, array('leName' => 'name')));

final public readColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Reads the ordered/reversed column map for certain model

<?php

print_r($metaData->readColumnMap(new Robots()));

final public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index) inherited from Phalcon\Mvc\Model\MetaData

Reads column-map information for certain model using a MODEL_* constant

<?php

print_r($metaData->readColumnMapIndex(new Robots(), MetaData::MODELS_REVERSE_COLUMN_MAP));

public getAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns table attributes names (fields)

<?php

print_r($metaData->getAttributes(new Robots()));

public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are part of the primary key

<?php

print_r($metaData->getPrimaryKeyAttributes(new Robots()));

public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of fields which are not part of the primary key

<?php

print_r($metaData->getNonPrimaryKeyAttributes(new Robots()));

public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns an array of not null attributes

<?php

print_r($metaData->getNotNullAttributes(new Robots()));

public getDataTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their data types

<?php

print_r($metaData->getDataTypes(new Robots()));

public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes which types are numerical

<?php

print_r($metaData->getDataTypesNumeric(new Robots()));

public string getIdentityField (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the name of identity field (if one is present)

<?php

print_r($metaData->getIdentityField(new Robots()));

public getBindTypes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes and their bind data types

<?php

print_r($metaData->getBindTypes(new Robots()));

public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the INSERT SQL generation

<?php

print_r($metaData->getAutomaticCreateAttributes(new Robots()));

public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes that must be ignored from the UPDATE SQL generation

<?php

print_r($metaData->getAutomaticUpdateAttributes(new Robots()));

public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the INSERT SQL generation

<?php

$metaData->setAutomaticCreateAttributes(new Robots(), array('created_at' => true));

public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that must be ignored from the UPDATE SQL generation

<?php

$metaData->setAutomaticUpdateAttributes(new Robots(), array('modified_at' => true));

public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes) inherited from Phalcon\Mvc\Model\MetaData

Set the attributes that allow empty string values

<?php

$metaData->setEmptyStringAttributes(new Robots(), array('name' => true));

public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes allow empty strings

<?php

print_r($metaData->getEmptyStringAttributes(new Robots()));

public getDefaultValues (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns attributes (which have default values) and their default values

<?php

print_r($metaData->getDefaultValues(new Robots()));

public getColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the column map if any

<?php

print_r($metaData->getColumnMap(new Robots()));

public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model) inherited from Phalcon\Mvc\Model\MetaData

Returns the reverse column map if any

<?php

print_r($metaData->getReverseColumnMap(new Robots()));

public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute) inherited from Phalcon\Mvc\Model\MetaData

Check if a model has certain attribute

<?php

var_dump($metaData->hasAttribute(new Robots(), 'name'));

public isEmpty () inherited from Phalcon\Mvc\Model\MetaData

Checks if the internal meta-data container is empty

<?php

var_dump($metaData->isEmpty());

public reset () inherited from Phalcon\Mvc\Model\MetaData

Resets internal meta-data in order to regenerate it

<?php

$metaData->reset();
Class Phalcon\Mvc\Model\Query

implements Phalcon\Mvc\Model\QueryInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

This class takes a PHQL intermediate representation and executes it.

<?php

 $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b
          WHERE b.name = :name: ORDER BY c.name";

 $result = $manager->executeQuery($phql, array(
   "name" => "Lamborghini"
 ));

 foreach ($result as $row) {
   echo "Name: ",  $row->cars->name, "\n";
   echo "Price: ", $row->cars->price, "\n";
   echo "Taxes: ", $row->taxes, "\n";
 }
Constants

integer TYPE_SELECT

integer TYPE_INSERT

integer TYPE_UPDATE

integer TYPE_DELETE

Methods

public __construct ([string $phql], [Phalcon\DiInterface $dependencyInjector], [mixed $options])

Phalcon\Mvc\Model\Query constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public getDI ()

Returns the dependency injection container

public setUniqueRow (mixed $uniqueRow)

Tells to the query if only the first row in the resultset must be returned

public getUniqueRow ()

Check if the query is programmed to get only the first row in the resultset

final protected _getQualified (array $expr)

Replaces the model’s name to its source name in a qualified-name expression

final protected _getCallArgument (array $argument)

Resolves an expression in a single call argument

final protected _getCaseExpression (array $expr)

Resolves an expression in a single call argument

final protected _getFunctionCall (array $expr)

Resolves an expression in a single call argument

final protected string _getExpression (array $expr, [boolean $quoting])

Resolves an expression from its intermediate code into a string

final protected _getSelectColumn (array $column)

Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex

final protected string _getTable (Phalcon\Mvc\Model\ManagerInterface $manager, array $qualifiedName)

Resolves a table in a SELECT statement checking if the model exists

final protected _getJoin (Phalcon\Mvc\Model\ManagerInterface $manager, mixed $join)

Resolves a JOIN clause checking if the associated models exist

final protected string _getJoinType (array $join)

Resolves a JOIN type

final protected array _getSingleJoin (string $joinType, string $joinSource, string $modelAlias, string $joinAlias, Phalcon\Mvc\Model\RelationInterface $relation)

Resolves joins involving has-one/belongs-to/has-many relations

final protected array _getMultiJoin (string $joinType, string $joinSource, string $modelAlias, string $joinAlias, Phalcon\Mvc\Model\RelationInterface $relation)

Resolves joins involving many-to-many relations

final protected array _getJoins (array $select)

Processes the JOINs in the query returning an internal representation for the database dialect

final protected array _getOrderClause (array | string $order)

Returns a processed order clause for a SELECT statement

final protected _getGroupClause (array $group)

Returns a processed group clause for a SELECT statement

final protected _getLimitClause (array $limitClause)

Returns a processed limit clause for a SELECT statement

final protected _prepareSelect ([mixed $ast], [mixed $merge])

Analyzes a SELECT intermediate code and produces an array to be executed later

final protected _prepareInsert ()

Analyzes an INSERT intermediate code and produces an array to be executed later

final protected _prepareUpdate ()

Analyzes an UPDATE intermediate code and produces an array to be executed later

final protected _prepareDelete ()

Analyzes a DELETE intermediate code and produces an array to be executed later

public parse ()

Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query

public getCache ()

Returns the current cache backend instance

final protected _executeSelect (mixed $intermediate, mixed $bindParams, mixed $bindTypes, [mixed $simulate])

Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset

final protected Phalcon\Mvc\Model\Query\StatusInterface _executeInsert (array $intermediate, array $bindParams, array $bindTypes)

Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status

final protected Phalcon\Mvc\Model\Query\StatusInterface _executeUpdate (array $intermediate, array $bindParams, array $bindTypes)

Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

final protected Phalcon\Mvc\Model\Query\StatusInterface _executeDelete (array $intermediate, array $bindParams, array $bindTypes)

Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

final protected Phalcon\Mvc\Model\ResultsetInterface _getRelatedRecords (Phalcon\Mvc\ModelInterface $model, array $intermediate, array $bindParams, array $bindTypes)

Query the records on which the UPDATE/DELETE operation well be done

public mixed execute ([array $bindParams], [array $bindTypes])

Executes a parsed PHQL statement

public Phalcon\Mvc\ModelInterface getSingleResult ([array $bindParams], [array $bindTypes])

Executes the query returning the first result

public setType (mixed $type)

Sets the type of PHQL statement to be executed

public getType ()

Gets the type of PHQL statement executed

public setBindParams (array $bindParams, [mixed $merge])

Set default bind parameters

public array getBindParams ()

Returns default bind params

public setBindTypes (array $bindTypes, [mixed $merge])

Set default bind parameters

public setSharedLock ([mixed $sharedLock])

Set SHARED LOCK clause

public array getBindTypes ()

Returns default bind types

public setIntermediate (array $intermediate)

Allows to set the IR to be executed

public array getIntermediate ()

Returns the intermediate representation of the PHQL statement

public cache (mixed $cacheOptions)

Sets the cache parameters of the query

public getCacheOptions ()

Returns the current cache options

public getSql ()

Returns the SQL to be generated by the internal PHQL (only works in SELECT statements)

public static clean ()

Destroys the internal PHQL cache

Class Phalcon\Mvc\Model\Query\Builder

implements Phalcon\Mvc\Model\Query\BuilderInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Helps to create PHQL queries using an OO interface

<?php

 $params = array(
    'models'     => array('Users'),
    'columns'    => array('id', 'name', 'status'),
    'conditions' => array(
        array(
            "created > :min: AND created < :max:",
            array("min" => '2013-01-01',   'max' => '2014-01-01'),
            array("min" => PDO::PARAM_STR, 'max' => PDO::PARAM_STR),
        ),
    ),
    // or 'conditions' => "created > '2013-01-01' AND created < '2014-01-01'",
    'group'      => array('id', 'name'),
    'having'     => "name = 'Kamil'",
    'order'      => array('name', 'id'),
    'limit'      => 20,
    'offset'     => 20,
    // or 'limit' => array(20, 20),
);
$queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params);
Constants

string OPERATOR_OR

string OPERATOR_AND

Methods

public __construct ([mixed $params], [Phalcon\DiInterface $dependencyInjector])

Phalcon\Mvc\Model\Query\Builder constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public distinct (mixed $distinct)

Sets SELECT DISTINCT / SELECT ALL flag

<?php

$builder->distinct("status");
$builder->distinct(null);

public getDistinct ()

Returns SELECT DISTINCT / SELECT ALL flag

public columns (mixed $columns)

Sets the columns to be queried

<?php

$builder->columns("id, name");
$builder->columns(array('id', 'name'));
  $builder->columns(array('name', 'number' => 'COUNT(*)'));

public string | array getColumns ()

Return the columns to be queried

public from (mixed $models)

Sets the models who makes part of the query

<?php

$builder->from('Robots');
$builder->from(array('Robots', 'RobotsParts'));
$builder->from(array('r' => 'Robots', 'rp' => 'RobotsParts'));

public addFrom (mixed $model, [mixed $alias], [mixed $with])

Add a model to take part of the query

<?php

  // Load data from models Robots
$builder->addFrom('Robots');

  // Load data from model 'Robots' using 'r' as alias in PHQL
$builder->addFrom('Robots', 'r');

  // Load data from model 'Robots' using 'r' as alias in PHQL
  // and eager load model 'RobotsParts'
$builder->addFrom('Robots', 'r', 'RobotsParts');

  // Load data from model 'Robots' using 'r' as alias in PHQL
  // and eager load models 'RobotsParts' and 'Parts'
$builder->addFrom('Robots', 'r', ['RobotsParts', 'Parts']);

public string | array getFrom ()

Return the models who makes part of the query

public Phalcon\Mvc\Model\Query\Builder join (string $model, [string $conditions], [string $alias], [string $type])

Adds an INNER join to the query

<?php

  // Inner Join model 'Robots' with automatic conditions and alias
$builder->join('Robots');

  // Inner Join model 'Robots' specifing conditions
$builder->join('Robots', 'Robots.id = RobotsParts.robots_id');

  // Inner Join model 'Robots' specifing conditions and alias
$builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r');

  // Left Join model 'Robots' specifing conditions, alias and type of join
$builder->join('Robots', 'r.id = RobotsParts.robots_id', 'r', 'LEFT');

public Phalcon\Mvc\Model\Query\Builder innerJoin (string $model, [string $conditions], [string $alias])

Adds an INNER join to the query

<?php

  // Inner Join model 'Robots' with automatic conditions and alias
$builder->innerJoin('Robots');

  // Inner Join model 'Robots' specifing conditions
$builder->innerJoin('Robots', 'Robots.id = RobotsParts.robots_id');

  // Inner Join model 'Robots' specifing conditions and alias
$builder->innerJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public Phalcon\Mvc\Model\Query\Builder leftJoin (string $model, [string $conditions], [string $alias])

Adds a LEFT join to the query

<?php

$builder->leftJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public Phalcon\Mvc\Model\Query\Builder rightJoin (string $model, [string $conditions], [string $alias])

Adds a RIGHT join to the query

<?php

$builder->rightJoin('Robots', 'r.id = RobotsParts.robots_id', 'r');

public array getJoins ()

Return join parts of the query

public Phalcon\Mvc\Model\Query\Builder where (mixed $conditions, [array $bindParams], [array $bindTypes])

Sets the query conditions

<?php

$builder->where(100);
$builder->where('name = "Peter"');
$builder->where('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100));

public Phalcon\Mvc\Model\Query\Builder andWhere (string $conditions, [array $bindParams], [array $bindTypes])

Appends a condition to the current conditions using a AND operator

<?php

$builder->andWhere('name = "Peter"');
$builder->andWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100));

public Phalcon\Mvc\Model\Query\Builder orWhere (string $conditions, [array $bindParams], [array $bindTypes])

Appends a condition to the current conditions using an OR operator

<?php

$builder->orWhere('name = "Peter"');
$builder->orWhere('name = :name: AND id > :id:', array('name' => 'Peter', 'id' => 100));

public betweenWhere (mixed $expr, mixed $minimum, mixed $maximum, [mixed $operator])

Appends a BETWEEN condition to the current conditions

<?php

$builder->betweenWhere('price', 100.25, 200.50);

public notBetweenWhere (mixed $expr, mixed $minimum, mixed $maximum, [mixed $operator])

Appends a NOT BETWEEN condition to the current conditions

<?php

$builder->notBetweenWhere('price', 100.25, 200.50);

public inWhere (mixed $expr, array $values, [mixed $operator])

Appends an IN condition to the current conditions

<?php

$builder->inWhere('id', [1, 2, 3]);

public notInWhere (mixed $expr, array $values, [mixed $operator])

Appends a NOT IN condition to the current conditions

<?php

$builder->notInWhere('id', [1, 2, 3]);

public string | array getWhere ()

Return the conditions for the query

public Phalcon\Mvc\Model\Query\Builder orderBy (string | array $orderBy)

Sets an ORDER BY condition clause

<?php

$builder->orderBy('Robots.name');
$builder->orderBy(array('1', 'Robots.name'));

public string | array getOrderBy ()

Returns the set ORDER BY clause

public having (mixed $having)

Sets a HAVING condition clause. You need to escape PHQL reserved words using [ and ] delimiters

<?php

$builder->having('SUM(Robots.price) > 0');

public forUpdate (mixed $forUpdate)

Sets a FOR UPDATE clause

<?php

$builder->forUpdate(true);

public string | array getHaving ()

Return the current having clause

public limit ([mixed $limit], [mixed $offset])

Sets a LIMIT clause, optionally an offset clause

<?php

$builder->limit(100);
$builder->limit(100, 20);

public string | array getLimit ()

Returns the current LIMIT clause

public offset (mixed $offset)

Sets an OFFSET clause

<?php

$builder->offset(30);

public string | array getOffset ()

Returns the current OFFSET clause

public Phalcon\Mvc\Model\Query\Builder groupBy (string | array $group)

Sets a GROUP BY clause

<?php

$builder->groupBy(array('Robots.name'));

public string getGroupBy ()

Returns the GROUP BY clause

final public string getPhql ()

Returns a PHQL statement built based on the builder parameters

public getQuery ()

Returns the query built

final public autoescape (mixed $identifier)

Automatically escapes identifiers but only if they need to be escaped.

Abstract class Phalcon\Mvc\Model\Query\Lang

Source on GitHub

PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model. To achieve the highest performance possible, we wrote 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.

<?php

 $intermediate = Phalcon\Mvc\Model\Query\Lang::parsePHQL("SELECT r.* FROM Robots r LIMIT 10");
Methods

public static string parsePHQL (string $phql)

Parses a PHQL statement returning an intermediate representation (IR)

Class Phalcon\Mvc\Model\Query\Status

implements Phalcon\Mvc\Model\Query\StatusInterface

Source on GitHub

This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails

<?php

$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$status = $app->modelsManager->executeQuery($phql, array(
   'id' => 100,
   'name' => 'Astroy Boy',
   'type' => 'mechanical',
   'year' => 1959
));

\//Check if the update was successful
if ($status->success() == true) {
   echo 'OK';
}
Methods

public __construct (mixed $success, [Phalcon\Mvc\ModelInterface $model])

public getModel ()

Returns the model that executed the action

public getMessages ()

Returns the messages produced because of a failed operation

public success ()

Allows to check if the executed operation was successful

Class Phalcon\Mvc\Model\Relation

implements Phalcon\Mvc\Model\RelationInterface

Source on GitHub

This class represents a relationship between two models

Constants

integer BELONGS_TO

integer HAS_ONE

integer HAS_MANY

integer HAS_ONE_THROUGH

integer HAS_MANY_THROUGH

integer NO_ACTION

integer ACTION_RESTRICT

integer ACTION_CASCADE

Methods

public __construct (int $type, string $referencedModel, string | array $fields, string | array $referencedFields, [array $options])

Phalcon\Mvc\Model\Relation constructor

public setIntermediateRelation (string | array $intermediateFields, string $intermediateModel, string $intermediateReferencedFields)

Sets the intermediate model data for has-*-through relations

public getType ()

Returns the relation type

public getReferencedModel ()

Returns the referenced model

public string | array getFields ()

Returns the fields

public string | array getReferencedFields ()

Returns the referenced fields

public string | array getOptions ()

Returns the options

public getOption (mixed $name)

Returns an option by the specified name If the option doesn’t exist null is returned

public isForeignKey ()

Check whether the relation act as a foreign key

public string | array getForeignKey ()

Returns the foreign key configuration

public array getParams ()

Returns parameters that must be always used when the related records are obtained

public isThrough ()

Check whether the relation is a ‘many-to-many’ relation or not

public isReusable ()

Check if records returned by getting belongs-to/has-many are implicitly cached during the current request

public string | array getIntermediateFields ()

Gets the intermediate fields for has-*-through relations

public getIntermediateModel ()

Gets the intermediate model for has-*-through relations

public string | array getIntermediateReferencedFields ()

Gets the intermediate referenced fields for has-*-through relations

Abstract class Phalcon\Mvc\Model\Resultset

implements Phalcon\Mvc\Model\ResultsetInterface, Iterator, Traversable, SeekableIterator, Countable, ArrayAccess, Serializable, JsonSerializable

Source on GitHub

This component allows to Phalcon\Mvc\Model returns large resultsets with the minimum memory consumption Resultsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing.

<?php

 // Using a standard foreach
 $robots = Robots::find(["type='virtual'", 'order' => 'name']);
 foreach ($robots as robot) {
     echo robot->name, "\n";
 }

 // Using a while
 $robots = Robots::find(["type='virtual'", 'order' => 'name');
 $robots->rewind();
 while ($robots->valid()) {
     $robot = $robots->current();
     echo $robot->name, "\n";
     $robots->next();
 }
Constants

integer TYPE_RESULT_FULL

integer TYPE_RESULT_PARTIAL

integer HYDRATE_RECORDS

integer HYDRATE_OBJECTS

integer HYDRATE_ARRAYS

Methods

public __construct (Phalcon\Db\ResultInterface | false $result, [Phalcon\Cache\BackendInterface $cache])

Phalcon\Mvc\Model\Resultset constructor

public next ()

Moves cursor to next row in the resultset

public valid ()

Check whether internal resource has rows to fetch

public key ()

Gets pointer number of active row in the resultset

final public rewind ()

Rewinds resultset to its beginning

final public seek (mixed $position)

Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row

final public count ()

Counts how many rows are in the resultset

public offsetExists (mixed $index)

Checks whether offset exists in the resultset

public offsetGet (mixed $index)

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\ModelInterface $value)

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (mixed $offset)

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public getType ()

Returns the internal type of data retrieval that the resultset is using

public getFirst ()

Get first row in the resultset

public getLast ()

Get last row in the resultset

public setIsFresh (mixed $isFresh)

Set if the resultset is fresh or an old one cached

public isFresh ()

Tell if the resultset if fresh or an old one cached

public setHydrateMode (mixed $hydrateMode)

Sets the hydration mode in the resultset

public getHydrateMode ()

Returns the current hydration mode

public getCache ()

Returns the associated cache for the resultset

public getMessages ()

Returns the error messages produced by a batch operation

public boolean update (array $data, [Closure $conditionCallback])

Updates every record in the resultset

public delete ([Closure $conditionCallback])

Deletes every record in the resultset

public Phalcon\Mvc\Model[] filter (callback $filter)

Filters a resultset returning only those the developer requires

<?php

 $filtered = $robots->filter(function($robot){
    if ($robot->id < 3) {
            return $robot;
    }
});

public array jsonSerialize ()

Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present

<?php

 $robots = Robots::find();
 echo json_encode($robots);

abstract public toArray () inherited from Phalcon\Mvc\Model\ResultsetInterface

...

abstract public current () inherited from Iterator

...

abstract public serialize () inherited from Serializable

...

abstract public unserialize (mixed $serialized) inherited from Serializable

...

Class Phalcon\Mvc\Model\Resultset\Complex

extends abstract class Phalcon\Mvc\Model\Resultset

implements JsonSerializable, Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface

Source on GitHub

Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required

Constants

integer TYPE_RESULT_FULL

integer TYPE_RESULT_PARTIAL

integer HYDRATE_RECORDS

integer HYDRATE_OBJECTS

integer HYDRATE_ARRAYS

Methods

public __construct (array $columnTypes, [Phalcon\Db\ResultInterface $result], [Phalcon\Cache\BackendInterface $cache])

Phalcon\Mvc\Model\Resultset\Complex constructor

final public current ()

Returns current row in the resultset

public toArray ()

Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does.

public serialize ()

Serializing a resultset will dump all related rows into a big array

public unserialize (mixed $data)

Unserializing a resultset will allow to only works on the rows present in the saved state

public next () inherited from Phalcon\Mvc\Model\Resultset

Moves cursor to next row in the resultset

public valid () inherited from Phalcon\Mvc\Model\Resultset

Check whether internal resource has rows to fetch

public key () inherited from Phalcon\Mvc\Model\Resultset

Gets pointer number of active row in the resultset

final public rewind () inherited from Phalcon\Mvc\Model\Resultset

Rewinds resultset to its beginning

final public seek (mixed $position) inherited from Phalcon\Mvc\Model\Resultset

Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row

final public count () inherited from Phalcon\Mvc\Model\Resultset

Counts how many rows are in the resultset

public offsetExists (mixed $index) inherited from Phalcon\Mvc\Model\Resultset

Checks whether offset exists in the resultset

public offsetGet (mixed $index) inherited from Phalcon\Mvc\Model\Resultset

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\ModelInterface $value) inherited from Phalcon\Mvc\Model\Resultset

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (mixed $offset) inherited from Phalcon\Mvc\Model\Resultset

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public getType () inherited from Phalcon\Mvc\Model\Resultset

Returns the internal type of data retrieval that the resultset is using

public getFirst () inherited from Phalcon\Mvc\Model\Resultset

Get first row in the resultset

public getLast () inherited from Phalcon\Mvc\Model\Resultset

Get last row in the resultset

public setIsFresh (mixed $isFresh) inherited from Phalcon\Mvc\Model\Resultset

Set if the resultset is fresh or an old one cached

public isFresh () inherited from Phalcon\Mvc\Model\Resultset

Tell if the resultset if fresh or an old one cached

public setHydrateMode (mixed $hydrateMode) inherited from Phalcon\Mvc\Model\Resultset

Sets the hydration mode in the resultset

public getHydrateMode () inherited from Phalcon\Mvc\Model\Resultset

Returns the current hydration mode

public getCache () inherited from Phalcon\Mvc\Model\Resultset

Returns the associated cache for the resultset

public getMessages () inherited from Phalcon\Mvc\Model\Resultset

Returns the error messages produced by a batch operation

public boolean update (array $data, [Closure $conditionCallback]) inherited from Phalcon\Mvc\Model\Resultset

Updates every record in the resultset

public delete ([Closure $conditionCallback]) inherited from Phalcon\Mvc\Model\Resultset

Deletes every record in the resultset

public Phalcon\Mvc\Model[] filter (callback $filter) inherited from Phalcon\Mvc\Model\Resultset

Filters a resultset returning only those the developer requires

<?php

 $filtered = $robots->filter(function($robot){
    if ($robot->id < 3) {
            return $robot;
    }
});

public array jsonSerialize () inherited from Phalcon\Mvc\Model\Resultset

Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present

<?php

 $robots = Robots::find();
 echo json_encode($robots);
Class Phalcon\Mvc\Model\Resultset\Simple

extends abstract class Phalcon\Mvc\Model\Resultset

implements JsonSerializable, Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface

Source on GitHub

Simple resultsets only contains a complete objects This class builds every complete object as it is required

Constants

integer TYPE_RESULT_FULL

integer TYPE_RESULT_PARTIAL

integer HYDRATE_RECORDS

integer HYDRATE_OBJECTS

integer HYDRATE_ARRAYS

Methods

public __construct (array $columnMap, Phalcon\Mvc\ModelInterface | Phalcon\Mvc\Model\Row $model, Phalcon\Db\Result\Pdo | null $result, [Phalcon\Cache\BackendInterface $cache], [boolean $keepSnapshots])

Phalcon\Mvc\Model\Resultset\Simple constructor

final public current ()

Returns current row in the resultset

public toArray ([mixed $renameColumns])

Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn’t be faster with a large number of records

public serialize ()

Serializing a resultset will dump all related rows into a big array

public unserialize (mixed $data)

Unserializing a resultset will allow to only works on the rows present in the saved state

public next () inherited from Phalcon\Mvc\Model\Resultset

Moves cursor to next row in the resultset

public valid () inherited from Phalcon\Mvc\Model\Resultset

Check whether internal resource has rows to fetch

public key () inherited from Phalcon\Mvc\Model\Resultset

Gets pointer number of active row in the resultset

final public rewind () inherited from Phalcon\Mvc\Model\Resultset

Rewinds resultset to its beginning

final public seek (mixed $position) inherited from Phalcon\Mvc\Model\Resultset

Changes internal pointer to a specific position in the resultset Set new position if required and set this->_row

final public count () inherited from Phalcon\Mvc\Model\Resultset

Counts how many rows are in the resultset

public offsetExists (mixed $index) inherited from Phalcon\Mvc\Model\Resultset

Checks whether offset exists in the resultset

public offsetGet (mixed $index) inherited from Phalcon\Mvc\Model\Resultset

Gets row in a specific position of the resultset

public offsetSet (int $index, Phalcon\Mvc\ModelInterface $value) inherited from Phalcon\Mvc\Model\Resultset

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (mixed $offset) inherited from Phalcon\Mvc\Model\Resultset

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public getType () inherited from Phalcon\Mvc\Model\Resultset

Returns the internal type of data retrieval that the resultset is using

public getFirst () inherited from Phalcon\Mvc\Model\Resultset

Get first row in the resultset

public getLast () inherited from Phalcon\Mvc\Model\Resultset

Get last row in the resultset

public setIsFresh (mixed $isFresh) inherited from Phalcon\Mvc\Model\Resultset

Set if the resultset is fresh or an old one cached

public isFresh () inherited from Phalcon\Mvc\Model\Resultset

Tell if the resultset if fresh or an old one cached

public setHydrateMode (mixed $hydrateMode) inherited from Phalcon\Mvc\Model\Resultset

Sets the hydration mode in the resultset

public getHydrateMode () inherited from Phalcon\Mvc\Model\Resultset

Returns the current hydration mode

public getCache () inherited from Phalcon\Mvc\Model\Resultset

Returns the associated cache for the resultset

public getMessages () inherited from Phalcon\Mvc\Model\Resultset

Returns the error messages produced by a batch operation

public boolean update (array $data, [Closure $conditionCallback]) inherited from Phalcon\Mvc\Model\Resultset

Updates every record in the resultset

public delete ([Closure $conditionCallback]) inherited from Phalcon\Mvc\Model\Resultset

Deletes every record in the resultset

public Phalcon\Mvc\Model[] filter (callback $filter) inherited from Phalcon\Mvc\Model\Resultset

Filters a resultset returning only those the developer requires

<?php

 $filtered = $robots->filter(function($robot){
    if ($robot->id < 3) {
            return $robot;
    }
});

public array jsonSerialize () inherited from Phalcon\Mvc\Model\Resultset

Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present

<?php

 $robots = Robots::find();
 echo json_encode($robots);
Class Phalcon\Mvc\Model\Row

implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\Model\ResultInterface, ArrayAccess, JsonSerializable

Source on GitHub

This component allows Phalcon\Mvc\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x].

Methods

public setDirtyState (mixed $dirtyState)

Set the current object’s state

public boolean offsetExists (string | int $index)

Checks whether offset exists in the row

public string | Phalcon\Mvc\ModelInterface offsetGet (string | int $index)

Gets a record in a specific position of the row

public offsetSet (string | int $index, Phalcon\Mvc\ModelInterface $value)

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public offsetUnset (string | int $offset)

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

public mixed readAttribute (string $attribute)

Reads an attribute value by its name

<?php

  echo $robot->readAttribute('name');

public writeAttribute (string $attribute, mixed $value)

Writes an attribute value by its name

<?php

  $robot->writeAttribute('name', 'Rosey');

public array toArray ()

Returns the instance as an array representation

public array jsonSerialize ()

Serializes the object for json_encode

Class Phalcon\Mvc\Model\Transaction

implements Phalcon\Mvc\Model\TransactionInterface

Source on GitHub

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\Transaction\Manager.

<?php

try {

  $manager = new \Phalcon\Mvc\Model\Transaction\Manager();

  $transaction = $manager->get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if ($robot->save() == false) {
    $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if ($robotPart->save() == false) {
    $transaction->rollback("Can't save robot part");
  }

  $transaction->commit();

} catch(Phalcon\Mvc\Model\Transaction\Failed $e) {
  echo 'Failed, reason: ', $e->getMessage();
}
Methods

public __construct (Phalcon\DiInterface $dependencyInjector, [boolean $autoBegin], [string $service])

Phalcon\Mvc\Model\Transaction constructor

public setTransactionManager (Phalcon\Mvc\Model\Transaction\ManagerInterface $manager)

Sets transaction manager related to the transaction

public begin ()

Starts the transaction

public commit ()

Commits the transaction

public boolean rollback ([string $rollbackMessage], [Phalcon\Mvc\ModelInterface $rollbackRecord])

Rollbacks the transaction

public getConnection ()

Returns the connection related to transaction

public setIsNewTransaction (mixed $isNew)

Sets if is a reused transaction or new once

public setRollbackOnAbort (mixed $rollbackOnAbort)

Sets flag to rollback on abort the HTTP connection

public isManaged ()

Checks whether transaction is managed by a transaction manager

public getMessages ()

Returns validations messages from last save try

public isValid ()

Checks whether internal connection is under an active transaction

public setRollbackedRecord (Phalcon\Mvc\ModelInterface $record)

Sets object which generates rollback action

Class Phalcon\Mvc\Model\Transaction\Exception

extends class Phalcon\Mvc\Model\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Transaction\Failed

extends class Phalcon\Mvc\Model\Transaction\Exception

implements Throwable

Source on GitHub

This class will be thrown to exit a try/catch block for isolated transactions

Methods

public __construct (mixed $message, [Phalcon\Mvc\ModelInterface $record])

Phalcon\Mvc\Model\Transaction\Failed constructor

public getRecordMessages ()

Returns validation record messages which stop the transaction

public getRecord ()

Returns validation record messages which stop the transaction

final private Exception __clone () inherited from Exception

Clone the exception

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Model\Transaction\Manager

implements Phalcon\Mvc\Model\Transaction\ManagerInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. This class manages the objects that compose a transaction. A transaction produces a unique connection that is passed to every object part of the transaction.

<?php

try {

  use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager;

  $transactionManager = new TransactionManager();

  $transaction = $transactionManager->get();

  $robot = new Robots();
  $robot->setTransaction($transaction);
  $robot->name = 'WALL·E';
  $robot->created_at = date('Y-m-d');
  if($robot->save()==false){
    $transaction->rollback("Can't save robot");
  }

  $robotPart = new RobotParts();
  $robotPart->setTransaction($transaction);
  $robotPart->type = 'head';
  if($robotPart->save()==false){
    $transaction->rollback("Can't save robot part");
  }

  $transaction->commit();

} catch (Phalcon\Mvc\Model\Transaction\Failed $e) {
  echo 'Failed, reason: ', $e->getMessage();
}
Methods

public __construct ([Phalcon\DiInterface $dependencyInjector])

Phalcon\Mvc\Model\Transaction\Manager constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injection container

public getDI ()

Returns the dependency injection container

public setDbService (mixed $service)

Sets the database service used to run the isolated transactions

public string getDbService ()

Returns the database service used to isolate the transaction

public setRollbackPendent (mixed $rollbackPendent)

Set if the transaction manager must register a shutdown function to clean up pendent transactions

public getRollbackPendent ()

Check if the transaction manager is registering a shutdown function to clean up pendent transactions

public has ()

Checks whether the manager has an active transaction

public get ([mixed $autoBegin])

Returns a new \Phalcon\Mvc\Model\Transaction or an already created once This method registers a shutdown function to rollback active connections

public getOrCreateTransaction ([mixed $autoBegin])

Create/Returns a new transaction or an existing one

public rollbackPendent ()

Rollbacks active transactions within the manager

public commit ()

Commits active transactions within the manager

public rollback ([boolean $collect])

Rollbacks active transactions within the manager Collect will remove the transaction from the manager

public notifyRollback (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a rollbacked transaction

public notifyCommit (Phalcon\Mvc\Model\TransactionInterface $transaction)

Notifies the manager about a committed transaction

protected _collectTransaction (Phalcon\Mvc\Model\TransactionInterface $transaction)

Removes transactions from the TransactionManager

public collectTransactions ()

Remove all the transactions from the manager

Class Phalcon\Mvc\Model\ValidationFailed

extends class Phalcon\Mvc\Model\Exception

implements Throwable

Source on GitHub

This exception is generated when a model fails to save a record Phalcon\Mvc\Model must be set up to have this behavior

Methods

public __construct (Model $model, Message[] $validationMessages)

Phalcon\Mvc\Model\ValidationFailed constructor

public getModel ()

Returns the model that generated the messages

public getMessages ()

Returns the complete group of messages produced in the validation

final private Exception __clone () inherited from Exception

Clone the exception

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Mvc\Model\Validator

Source on GitHub

This is a base class for Phalcon\Mvc\Model validators

Methods

public __construct (array $options)

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type])

Appends a message to the validator

public getMessages ()

Returns messages generated by the validator

public array getOptions ()

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue])

Returns an option

public isSetOption (mixed $option)

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Email

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Allows to validate if email fields has correct values

<?php

use Phalcon\Mvc\Model\Validator\Email as EmailValidator;

class Subscriptors extends \Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new EmailValidator(array(
                    'field' => 'electronic_mail'
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }
}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Exclusionin

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Phalcon\Mvc\Model\Validator\ExclusionIn Check if a value is not included into a list of values

<?php

use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionInValidator;

class Subscriptors extends \Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new ExclusionInValidator(array(
                    'field' => 'status',
                    'domain' => array('A', 'I')
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Inclusionin

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Phalcon\Mvc\Model\Validator\InclusionIn Check if a value is included into a list of values

<?php

use Phalcon\Mvc\Model\Validator\InclusionIn as InclusionInValidator;

class Subscriptors extends \Phalcon\Mvc\Model
{

    public function validation()
    {
            $this->validate(new InclusionInValidator(array(
                    "field" => 'status',
                    'domain' => array('A', 'I')
            )));
            if ($this->validationHasFailed() == true) {
                    return false;
            }
    }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Ip

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Phalcon\Mvc\Model\Validator\IP Validates that a value is ipv4 address in valid range

<?php

use Phalcon\Mvc\Model\Validator\Ip;

class Data extends Phalcon\Mvc\Model
{

  public function validation()
  {
      // Any pubic IP
      $this->validate(new IP(array(
          'field'             => 'server_ip',
          'version'           => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified
          'allowReserved'     => false,   // False if not specified. Ignored for v6
          'allowPrivate'      => false,   // False if not specified
          'message'           => 'IP address has to be correct'
      )));

      // Any public v4 address
      $this->validate(new IP(array(
          'field'             => 'ip_4',
          'version'           => IP::VERSION_4,
          'message'           => 'IP address has to be correct'
      )));

      // Any v6 address
      $this->validate(new IP(array(
          'field'             => 'ip6',
          'version'           => IP::VERSION_6,
          'allowPrivate'      => true,
          'message'           => 'IP address has to be correct'
      )));

      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Constants

integer VERSION_4

integer VERSION_6

Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Numericality

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Allows to validate if a field has a valid numeric format

<?php

use Phalcon\Mvc\Model\Validator\Numericality as NumericalityValidator;

class Products extends \Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new NumericalityValidator(array(
          "field" => 'price'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\PresenceOf

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Allows to validate if a filed have a value different of null and empty string (“”)

<?php

use Phalcon\Mvc\Model\Validator\PresenceOf;

class Subscriptors extends \Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new PresenceOf(array(
          "field" => 'name',
          "message" => 'The name is required'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Regex

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Allows validate if the value of a field matches a regular expression

<?php

use Phalcon\Mvc\Model\Validator\Regex as RegexValidator;

class Subscriptors extends \Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new RegexValidator(array(
          "field" => 'created_at',
          'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])/'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\StringLength

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Simply validates specified string length constraints

<?php

use Phalcon\Mvc\Model\Validator\StringLength as StringLengthValidator;

class Subscriptors extends \Phalcon\Mvc\Model
{

public function validation()
{
    $this->validate(new StringLengthValidator(array(
            "field" => 'name_last',
            'max' => 50,
            'min' => 2,
            'messageMaximum' => 'We don\'t like really long names',
            'messageMinimum' => 'We want more than just their initials'
    )));
    if ($this->validationHasFailed() == true) {
            return false;
    }
}

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Uniqueness

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Validates that a field or a combination of a set of fields are not present more than once in the existing records of the related table

<?php

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Validator\Uniqueness;

class Subscriptors extends Model
{

  public function validation()
  {
      $this->validate(new Uniqueness(array(
          "field"   => "email",
          "message" => "Value of field 'email' is already present in another record"
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }
}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Model\Validator\Url

extends abstract class Phalcon\Mvc\Model\Validator

implements Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Allows to validate if a field has a url format

<?php

use Phalcon\Mvc\Model\Validator\Url as UrlValidator;

class Posts extends \Phalcon\Mvc\Model
{

  public function validation()
  {
      $this->validate(new UrlValidator(array(
          'field' => 'source_url'
      )));
      if ($this->validationHasFailed() == true) {
          return false;
      }
  }

}
Methods

public validate (Phalcon\Mvc\EntityInterface $record)

Executes the validator

public __construct (array $options) inherited from Phalcon\Mvc\Model\Validator

Phalcon\Mvc\Model\Validator constructor

protected appendMessage (string $message, [string | array $field], [string $type]) inherited from Phalcon\Mvc\Model\Validator

Appends a message to the validator

public getMessages () inherited from Phalcon\Mvc\Model\Validator

Returns messages generated by the validator

public array getOptions () inherited from Phalcon\Mvc\Model\Validator

Returns all the options from the validator

public getOption (mixed $option, [mixed $defaultValue]) inherited from Phalcon\Mvc\Model\Validator

Returns an option

public isSetOption (mixed $option) inherited from Phalcon\Mvc\Model\Validator

Check whether an option has been defined in the validator options

Class Phalcon\Mvc\Router

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\RouterInterface, Phalcon\Events\EventsAwareInterface

Source on GitHub

Phalcon\Mvc\Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request

<?php

 use Phalcon\Mvc\Router;

 $router = new Router();

 $router->add(
     '/documentation/{chapter}/{name}\.{type:[a-z]+}',
     [
         'controller' => 'documentation',
         'action'     => 'show'
    )
);

 $router->handle();

 echo $router->getControllerName();
Constants

integer URI_SOURCE_GET_URL

integer URI_SOURCE_SERVER_REQUEST_URI

integer POSITION_FIRST

integer POSITION_LAST

Methods

public __construct ([mixed $defaultRoutes])

Phalcon\Mvc\Router constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

Sets the events manager

public getEventsManager ()

Returns the internal event manager

public getRewriteUri ()

Get rewrite info. This info is read from $_GET[‘_url’]. This returns ‘/’ if the rewrite information cannot be read

public setUriSource (mixed $uriSource)

Sets the URI source. One of the URI_SOURCE_* constants

<?php

$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);

public removeExtraSlashes (mixed $remove)

Set whether router must remove the extra slashes in the handled routes

public setDefaultNamespace (mixed $namespaceName)

Sets the name of the default namespace

public setDefaultModule (mixed $moduleName)

Sets the name of the default module

public setDefaultController (mixed $controllerName)

Sets the default controller name

public setDefaultAction (mixed $actionName)

Sets the default action name

public setDefaults (array $defaults)

Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route

<?php

 $router->setDefaults([
     'module' => 'common',
     'action' => 'index'
 ]);

public getDefaults ()

Returns an array of default parameters

public handle ([mixed $uri])

Handles routing information received from the rewrite engine

<?php

 // Read the info from the rewrite engine
 $router->handle();

 // Manually passing an URL
 $router->handle('/posts/edit/1');

public add (mixed $pattern, [mixed $paths], [mixed $httpMethods], [mixed $position])

Adds a route to the router without any HTTP constraint

<?php

 use Phalcon\Mvc\Router;

 $router->add('/about', 'About::index');
 $router->add('/about', 'About::index', ['GET', 'POST']);
 $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST);

public addGet (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is GET

public addPost (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is POST

public addPut (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is PUT

public addPatch (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is PATCH

public addDelete (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is DELETE

public addOptions (mixed $pattern, [mixed $paths], [mixed $position])

Add a route to the router that only match if the HTTP method is OPTIONS

public addHead (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is HEAD

public addPurge (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support)

public addTrace (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is TRACE

public addConnect (mixed $pattern, [mixed $paths], [mixed $position])

Adds a route to the router that only match if the HTTP method is CONNECT

public mount (Phalcon\Mvc\Router\GroupInterface $group)

Mounts a group of routes in the router

public notFound (mixed $paths)

Set a group of paths to be returned when none of the defined routes are matched

public clear ()

Removes all the pre-defined routes

public getNamespaceName ()

Returns the processed namespace name

public getModuleName ()

Returns the processed module name

public getControllerName ()

Returns the processed controller name

public getActionName ()

Returns the processed action name

public getParams ()

Returns the processed parameters

public getMatchedRoute ()

Returns the route that matches the handled URI

public getMatches ()

Returns the sub expressions in the regular expression matched

public wasMatched ()

Checks if the router matches any of the defined routes

public getRoutes ()

Returns all the routes defined in the router

public getRouteById (mixed $id)

Returns a route object by its id

public getRouteByName (mixed $name)

Returns a route object by its name

public isExactControllerName ()

Returns whether controller name should not be mangled

Class Phalcon\Mvc\Router\Annotations

extends class Phalcon\Mvc\Router

implements Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\RouterInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

A router that reads routes annotations from classes/resources

<?php

 $di['router'] = function() {

    //Use the annotations router
    $router = new Annotations(false);

    //This will do the same as above but only if the handled uri starts with /robots
            $router->addResource('Robots', '/robots');

            return $router;
};
Constants

integer URI_SOURCE_GET_URL

integer URI_SOURCE_SERVER_REQUEST_URI

integer POSITION_FIRST

integer POSITION_LAST

Methods

public addResource (mixed $handler, [mixed $prefix])

Adds a resource to the annotations handler A resource is a class that contains routing annotations

public addModuleResource (mixed $module, mixed $handler, [mixed $prefix])

Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module

public handle ([mixed $uri])

Produce the routing parameters from the rewrite information

public processControllerAnnotation (mixed $handler, Phalcon\Annotations\Annotation $annotation)

Checks for annotations in the controller docblock

public processActionAnnotation (mixed $module, mixed $namespaceName, mixed $controller, mixed $action, Phalcon\Annotations\Annotation $annotation)

Checks for annotations in the public methods of the controller

public setControllerSuffix (mixed $controllerSuffix)

Changes the controller class suffix

public setActionSuffix (mixed $actionSuffix)

Changes the action method suffix

public getResources ()

Return the registered resources

public __construct ([mixed $defaultRoutes]) inherited from Phalcon\Mvc\Router

Phalcon\Mvc\Router constructor

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Mvc\Router

Sets the dependency injector

public getDI () inherited from Phalcon\Mvc\Router

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Mvc\Router

Sets the events manager

public getEventsManager () inherited from Phalcon\Mvc\Router

Returns the internal event manager

public getRewriteUri () inherited from Phalcon\Mvc\Router

Get rewrite info. This info is read from $_GET[‘_url’]. This returns ‘/’ if the rewrite information cannot be read

public setUriSource (mixed $uriSource) inherited from Phalcon\Mvc\Router

Sets the URI source. One of the URI_SOURCE_* constants

<?php

$router->setUriSource(Router::URI_SOURCE_SERVER_REQUEST_URI);

public removeExtraSlashes (mixed $remove) inherited from Phalcon\Mvc\Router

Set whether router must remove the extra slashes in the handled routes

public setDefaultNamespace (mixed $namespaceName) inherited from Phalcon\Mvc\Router

Sets the name of the default namespace

public setDefaultModule (mixed $moduleName) inherited from Phalcon\Mvc\Router

Sets the name of the default module

public setDefaultController (mixed $controllerName) inherited from Phalcon\Mvc\Router

Sets the default controller name

public setDefaultAction (mixed $actionName) inherited from Phalcon\Mvc\Router

Sets the default action name

public setDefaults (array $defaults) inherited from Phalcon\Mvc\Router

Sets an array of default paths. If a route is missing a path the router will use the defined here This method must not be used to set a 404 route

<?php

 $router->setDefaults([
     'module' => 'common',
     'action' => 'index'
 ]);

public getDefaults () inherited from Phalcon\Mvc\Router

Returns an array of default parameters

public add (mixed $pattern, [mixed $paths], [mixed $httpMethods], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router without any HTTP constraint

<?php

 use Phalcon\Mvc\Router;

 $router->add('/about', 'About::index');
 $router->add('/about', 'About::index', ['GET', 'POST']);
 $router->add('/about', 'About::index', ['GET', 'POST'], Router::POSITION_FIRST);

public addGet (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is GET

public addPost (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is POST

public addPut (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is PUT

public addPatch (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is PATCH

public addDelete (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is DELETE

public addOptions (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Add a route to the router that only match if the HTTP method is OPTIONS

public addHead (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is HEAD

public addPurge (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support)

public addTrace (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is TRACE

public addConnect (mixed $pattern, [mixed $paths], [mixed $position]) inherited from Phalcon\Mvc\Router

Adds a route to the router that only match if the HTTP method is CONNECT

public mount (Phalcon\Mvc\Router\GroupInterface $group) inherited from Phalcon\Mvc\Router

Mounts a group of routes in the router

public notFound (mixed $paths) inherited from Phalcon\Mvc\Router

Set a group of paths to be returned when none of the defined routes are matched

public clear () inherited from Phalcon\Mvc\Router

Removes all the pre-defined routes

public getNamespaceName () inherited from Phalcon\Mvc\Router

Returns the processed namespace name

public getModuleName () inherited from Phalcon\Mvc\Router

Returns the processed module name

public getControllerName () inherited from Phalcon\Mvc\Router

Returns the processed controller name

public getActionName () inherited from Phalcon\Mvc\Router

Returns the processed action name

public getParams () inherited from Phalcon\Mvc\Router

Returns the processed parameters

public getMatchedRoute () inherited from Phalcon\Mvc\Router

Returns the route that matches the handled URI

public getMatches () inherited from Phalcon\Mvc\Router

Returns the sub expressions in the regular expression matched

public wasMatched () inherited from Phalcon\Mvc\Router

Checks if the router matches any of the defined routes

public getRoutes () inherited from Phalcon\Mvc\Router

Returns all the routes defined in the router

public getRouteById (mixed $id) inherited from Phalcon\Mvc\Router

Returns a route object by its id

public getRouteByName (mixed $name) inherited from Phalcon\Mvc\Router

Returns a route object by its name

public isExactControllerName () inherited from Phalcon\Mvc\Router

Returns whether controller name should not be mangled

Class Phalcon\Mvc\Router\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\Router\Group

implements Phalcon\Mvc\Router\GroupInterface

Source on GitHub

Helper class to create a group of routes with common attributes

<?php

 $router = new \Phalcon\Mvc\Router();

 //Create a group with a common module and controller
 $blog = new Group(array(
    'module' => 'blog',
    'controller' => 'index'
 ));

 //All the routes start with /blog
 $blog->setPrefix('/blog');

 //Add a route to the group
 $blog->add('/save', array(
    'action' => 'save'
 ));

 //Add another route to the group
 $blog->add('/edit/{id}', array(
    'action' => 'edit'
 ));

 //This route maps to a controller different than the default
 $blog->add('/blog', array(
    'controller' => 'about',
    'action' => 'index'
 ));

 //Add the group to the router
 $router->mount($blog);
Methods

public __construct ([mixed $paths])

Phalcon\Mvc\Router\Group constructor

public setHostname (mixed $hostname)

Set a hostname restriction for all the routes in the group

public getHostname ()

Returns the hostname restriction

public setPrefix (mixed $prefix)

Set a common uri prefix for all the routes in this group

public getPrefix ()

Returns the common prefix for all the routes

public beforeMatch (mixed $beforeMatch)

Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched

public getBeforeMatch ()

Returns the ‘before match’ callback if any

public setPaths (mixed $paths)

Set common paths for all the routes in the group

public getPaths ()

Returns the common paths defined for this group

public getRoutes ()

Returns the routes added to the group

public add (mixed $pattern, [mixed $paths], [mixed $httpMethods])

Adds a route to the router on any HTTP method

<?php

 router->add('/about', 'About::index');

public Phalcon\Mvc\Router\Route addGet (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is GET

public Phalcon\Mvc\Router\Route addPost (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is POST

public Phalcon\Mvc\Router\Route addPut (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is PUT

public Phalcon\Mvc\Router\Route addPatch (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is PATCH

public Phalcon\Mvc\Router\Route addDelete (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is DELETE

public Phalcon\Mvc\Router\Route addOptions (string $pattern, [string/array $paths])

Add a route to the router that only match if the HTTP method is OPTIONS

public Phalcon\Mvc\Router\Route addHead (string $pattern, [string/array $paths])

Adds a route to the router that only match if the HTTP method is HEAD

public clear ()

Removes all the pre-defined routes

protected _addRoute (mixed $pattern, [mixed $paths], [mixed $httpMethods])

Adds a route applying the common attributes

Class Phalcon\Mvc\Router\Route

implements Phalcon\Mvc\Router\RouteInterface

Source on GitHub

This class represents every route added to the router

Methods

public __construct (mixed $pattern, [mixed $paths], [mixed $httpMethods])

Phalcon\Mvc\Router\Route constructor

public compilePattern (mixed $pattern)

Replaces placeholders from pattern returning a valid PCRE regular expression

public via (mixed $httpMethods)

Set one or more HTTP methods that constraint the matching of the route

<?php

 $route->via('GET');
 $route->via(array('GET', 'POST'));

public extractNamedParams (mixed $pattern)

Extracts parameters from a string

public reConfigure (mixed $pattern, [mixed $paths])

Reconfigure the route adding a new pattern and a set of paths

public static getRoutePaths ([mixed $paths])

Returns routePaths

public getName ()

Returns the route’s name

public setName (mixed $name)

Sets the route’s name

<?php

 $router->add('/about', array(
     'controller' => 'about'
 ))->setName('about');

public beforeMatch (mixed $callback)

Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched

<?php

 $router->add('/login', array(
  'module'     => 'admin',
  'controller' => 'session'
 ))->beforeMatch(function ($uri, $route) {
   // Check if the request was made with Ajax
   if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'xmlhttprequest') {
      return false;
   }
     return true;
 });

public getBeforeMatch ()

Returns the ‘before match’ callback if any

public match (mixed $callback)

Allows to set a callback to handle the request directly in the route

<?php

$router->add("/help", array())->match(function () {
  return $this->getResponse()->redirect('https://support.google.com/', true);
});

public getMatch ()

Returns the ‘match’ callback if any

public getRouteId ()

Returns the route’s id

public getPattern ()

Returns the route’s pattern

public getCompiledPattern ()

Returns the route’s compiled pattern

public getPaths ()

Returns the paths

public getReversedPaths ()

Returns the paths using positions as keys and names as values

public setHttpMethods (mixed $httpMethods)

Sets a set of HTTP methods that constraint the matching of the route (alias of via)

<?php

 $route->setHttpMethods('GET');
 $route->setHttpMethods(array('GET', 'POST'));

public getHttpMethods ()

Returns the HTTP methods that constraint matching the route

public setHostname (mixed $hostname)

Sets a hostname restriction to the route

<?php

 $route->setHostname('localhost');

public getHostname ()

Returns the hostname restriction if any

public setGroup (Phalcon\Mvc\Router\GroupInterface $group)

Sets the group associated with the route

public getGroup ()

Returns the group associated with the route

public convert (mixed $name, mixed $converter)

Adds a converter to perform an additional transformation for certain parameter

public getConverters ()

Returns the router converter

public static reset ()

Resets the internal route id generator

Class Phalcon\Mvc\Url

implements Phalcon\Mvc\UrlInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

This components helps in the generation of: URIs, URLs and Paths

<?php

 //Generate a URL appending the URI to the base URI
 echo $url->get('products/edit/1');

 //Generate a URL for a predefined route
 echo $url->get(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2012'));
Methods

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public setBaseUri (mixed $baseUri)

Sets a prefix for all the URIs to be generated

<?php

$url->setBaseUri('/invo/');
$url->setBaseUri('/invo/index.php/');

public setStaticBaseUri (mixed $staticBaseUri)

Sets a prefix for all static URLs generated

<?php

$url->setStaticBaseUri('/invo/');

public getBaseUri ()

Returns the prefix for all the generated urls. By default /

public getStaticBaseUri ()

Returns the prefix for all the generated static urls. By default /

public setBasePath (mixed $basePath)

Sets a base path for all the generated paths

<?php

$url->setBasePath('/var/www/htdocs/');

public getBasePath ()

Returns the base path

public get ([mixed $uri], [mixed $args], [mixed $local], [mixed $baseUri])

Generates a URL

<?php

 //Generate a URL appending the URI to the base URI
 echo $url->get('products/edit/1');

 //Generate a URL for a predefined route
 echo $url->get(array('for' => 'blog-post', 'title' => 'some-cool-stuff', 'year' => '2015'));

 // Generate a URL with GET arguments (/show/products?id=1&name=Carrots)
 echo $url->get('show/products', array('id' => 1, 'name' => 'Carrots'));

 // Generate an absolute URL by setting the third parameter as false.
 echo $url->get('https://phalconphp.com/', null, false);

public getStatic ([mixed $uri])

Generates a URL for a static resource

<?php

 // Generate a URL for a static resource
 echo $url->getStatic("img/logo.png");

 // Generate a URL for a static predefined route
 echo $url->getStatic(array('for' => 'logo-cdn'));

public path ([mixed $path])

Generates a local path

Class Phalcon\Mvc\Url\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\User\Component

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\User\Module

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\User\Plugin

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

Methods

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\View

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ViewInterface, Phalcon\Mvc\ViewBaseInterface

Source on GitHub

Phalcon\Mvc\View is a class for working with the “view” portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping.

<?php

 use Phalcon\Mvc\View;

 $view = new View();

 // Setting views directory
 $view->setViewsDir('app/views/');

 $view->start();

 // Shows recent posts view (app/views/posts/recent.phtml)
 $view->render('posts', 'recent');
 $view->finish();

 // Printing views output
 echo $view->getContent();
Constants

integer LEVEL_MAIN_LAYOUT

integer LEVEL_AFTER_TEMPLATE

integer LEVEL_LAYOUT

integer LEVEL_BEFORE_TEMPLATE

integer LEVEL_ACTION_VIEW

integer LEVEL_NO_RENDER

integer CACHE_MODE_NONE

integer CACHE_MODE_INVERSE

Methods

public getRenderLevel ()

...

public getCurrentRenderLevel ()

...

public getRegisteredEngines ()

public __construct ([array $options])

Phalcon\Mvc\View constructor

final protected _isAbsolutePath (mixed $path)

Checks if a path is absolute or not

public setViewsDir (mixed $viewsDir)

Sets the views directory. Depending of your platform, always add a trailing slash or backslash

public getViewsDir ()

Gets views directory

public setLayoutsDir (mixed $layoutsDir)

Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash

<?php

 $view->setLayoutsDir('../common/layouts/');

public getLayoutsDir ()

Gets the current layouts sub-directory

public setPartialsDir (mixed $partialsDir)

Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash

<?php

 $view->setPartialsDir('../common/partials/');

public getPartialsDir ()

Gets the current partials sub-directory

public setBasePath (mixed $basePath)

Sets base path. Depending of your platform, always add a trailing slash or backslash

<?php

    $view->setBasePath(__DIR__ . '/');

public getBasePath ()

Gets base path

public setRenderLevel (mixed $level)

Sets the render level for the view

<?php

    //Render the view related to the controller only
    $this->view->setRenderLevel(View::LEVEL_LAYOUT);

public disableLevel (mixed $level)

Disables a specific level of rendering

<?php

 // Render all levels except ACTION level
 $this->view->disableLevel(View::LEVEL_ACTION_VIEW);

public setMainView (mixed $viewPath)

Sets default view name. Must be a file without extension in the views directory

<?php

    //Renders as main view views-dir/base.phtml
    $this->view->setMainView('base');

public getMainView ()

Returns the name of the main view

public setLayout (mixed $layout)

Change the layout to be used instead of using the name of the latest controller name

<?php

    $this->view->setLayout('main');

public getLayout ()

Returns the name of the main view

public setTemplateBefore (mixed $templateBefore)

Sets a template before the controller layout

public cleanTemplateBefore ()

Resets any “template before” layouts

public setTemplateAfter (mixed $templateAfter)

Sets a “template after” controller layout

public cleanTemplateAfter ()

Resets any template before layouts

public setParamToView (mixed $key, mixed $value)

Adds parameters to views (alias of setVar)

<?php

$this->view->setParamToView('products', $products);

public setVars (array $params, [mixed $merge])

Set all the render params

<?php

$this->view->setVars(['products' => $products]);

public setVar (mixed $key, mixed $value)

Set a single view parameter

<?php

$this->view->setVar('products', $products);

public getVar (mixed $key)

Returns a parameter previously set in the view

public getParamsToView ()

Returns parameters to views

public getControllerName ()

Gets the name of the controller rendered

public getActionName ()

Gets the name of the action rendered

public getParams ()

Gets extra parameters of the action rendered

public start ()

Starts rendering process enabling the output buffering

protected _loadTemplateEngines ()

Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php

protected _engineRender (array $engines, string $viewPath, boolean $silence, boolean $mustClean, [Phalcon\Cache\BackendInterface $cache])

Checks whether view exists on registered extensions and render it

public registerEngines (array $engines)

Register templating engines

<?php

 $this->view->registerEngines([
  '.phtml' => 'Phalcon\Mvc\View\Engine\Php',
  '.volt'  => 'Phalcon\Mvc\View\Engine\Volt',
  '.mhtml' => 'MyCustomEngine'
 ]);

public exists (mixed $view)

Checks whether view exists

public render (string $controllerName, string $actionName, [array $params])

Executes render process from dispatching data

<?php

 // Shows recent posts view (app/views/posts/recent.phtml)
 $view->start()->render('posts', 'recent')->finish();

public pick (mixed $renderView)

Choose a different view to render instead of last-controller/last-action

<?php

 use Phalcon\Mvc\Controller;

 class ProductsController extends Controller
 {

    public function saveAction()
    {

         // Do some save stuff...

         // Then show the list view
         $this->view->pick("products/list");
    }
 }

public getPartial (mixed $partialPath, [mixed $params])

Renders a partial view

<?php

    // Retrieve the contents of a partial
    echo $this->getPartial('shared/footer');
<?php

    // Retrieve the contents of a partial with arguments
    echo $this->getPartial('shared/footer', ['content' => $html]);

public partial (mixed $partialPath, [mixed $params])

Renders a partial view

<?php

    // Show a partial inside another view
    $this->partial('shared/footer');
<?php

    // Show a partial inside another view with parameters
    $this->partial('shared/footer', ['content' => $html]);

public string getRender (string $controllerName, string $actionName, [array $params], [mixed $configCallback])

Perform the automatic rendering returning the output as a string

<?php

    $template = $this->view->getRender('products', 'show', ['products' => $products]);

public finish ()

Finishes the render process by stopping the output buffering

protected _createCache ()

Create a Phalcon\Cache based on the internal cache options

public isCaching ()

Check if the component is currently caching the output content

public getCache ()

Returns the cache instance used to cache

public cache ([mixed $options])

Cache the actual view render to certain level

<?php

  $this->view->cache(['key' => 'my-key', 'lifetime' => 86400]);

public setContent (mixed $content)

Externally sets the view content

<?php

$this->view->setContent("<h1>hello</h1>");

public getContent ()

Returns cached output from another view stage

public getActiveRenderPath ()

Returns the path (or paths) of the views that are currently rendered

public disable ()

Disables the auto-rendering process

public enable ()

Enables the auto-rendering process

public reset ()

Resets the view component to its factory default values

public __set (mixed $key, mixed $value)

Magic method to pass variables to the views

<?php

$this->view->products = $products;

public __get (mixed $key)

Magic method to retrieve a variable passed to the view

<?php

echo $this->view->products;

public isDisabled ()

Whether automatic rendering is enabled

public __isset (mixed $key)

Magic method to retrieve if a variable is set in the view

<?php

  echo isset($this->view->products);

protected getViewsDirs ()

Gets views directories

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

Abstract class Phalcon\Mvc\View\Engine

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface

Source on GitHub

All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.

Methods

public __construct (Phalcon\Mvc\ViewBaseInterface $view, [Phalcon\DiInterface $dependencyInjector])

Phalcon\Mvc\View\Engine constructor

public getContent ()

Returns cached output on another view stage

public string partial (string $partialPath, [array $params])

Renders a partial inside another view

public getView ()

Returns the view component related to the adapter

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Php

extends abstract class Phalcon\Mvc\View\Engine

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\View\EngineInterface

Source on GitHub

Adapter to use PHP itself as templating engine

Methods

public render (mixed $path, mixed $params, [mixed $mustClean])

Renders a view using the template engine

public __construct (Phalcon\Mvc\ViewBaseInterface $view, [Phalcon\DiInterface $dependencyInjector]) inherited from Phalcon\Mvc\View\Engine

Phalcon\Mvc\View\Engine constructor

public getContent () inherited from Phalcon\Mvc\View\Engine

Returns cached output on another view stage

public string partial (string $partialPath, [array $params]) inherited from Phalcon\Mvc\View\Engine

Renders a partial inside another view

public getView () inherited from Phalcon\Mvc\View\Engine

Returns the view component related to the adapter

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Volt

extends abstract class Phalcon\Mvc\View\Engine

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\View\EngineInterface

Source on GitHub

Designer friendly and fast template engine for PHP written in Zephir/C

Methods

public setOptions (array $options)

Set Volt’s options

public getOptions ()

Return Volt’s options

public getCompiler ()

Returns the Volt’s compiler

public render (mixed $templatePath, mixed $params, [mixed $mustClean])

Renders a view using the template engine

public length (mixed $item)

Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen

public isIncluded (mixed $needle, mixed $haystack)

Checks if the needle is included in the haystack

public convertEncoding (mixed $text, mixed $from, mixed $to)

Performs a string conversion

public slice (mixed $value, [mixed $start], [mixed $end])

Extracts a slice from a string/array/traversable object value

public sort (array $value)

Sorts an array

public callMacro (mixed $name, [array $arguments])

Checks if a macro is defined and calls it

public __construct (Phalcon\Mvc\ViewBaseInterface $view, [Phalcon\DiInterface $dependencyInjector]) inherited from Phalcon\Mvc\View\Engine

Phalcon\Mvc\View\Engine constructor

public getContent () inherited from Phalcon\Mvc\View\Engine

Returns cached output on another view stage

public string partial (string $partialPath, [array $params]) inherited from Phalcon\Mvc\View\Engine

Renders a partial inside another view

public getView () inherited from Phalcon\Mvc\View\Engine

Returns the view component related to the adapter

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Class Phalcon\Mvc\View\Engine\Volt\Compiler

implements Phalcon\Di\InjectionAwareInterface

Source on GitHub

This class reads and compiles Volt templates into PHP plain code

<?php

$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();

$compiler->compile('views/partials/header.volt');

require $compiler->getCompiledTemplatePath();
Methods

public __construct ([Phalcon\Mvc\ViewBaseInterface $view])

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setOptions (array $options)

Sets the compiler options

public setOption (string $option, mixed $value)

Sets a single compiler option

public string getOption (string $option)

Returns a compiler’s option

public getOptions ()

Returns the compiler options

final public mixed fireExtensionEvent (string $name, [array $arguments])

Fires an event to registered extensions

public addExtension (mixed $extension)

Registers a Volt’s extension

public getExtensions ()

Returns the list of extensions registered in Volt

public addFunction (mixed $name, mixed $definition)

Register a new function in the compiler

public getFunctions ()

Register the user registered functions

public addFilter (mixed $name, mixed $definition)

Register a new filter in the compiler

public getFilters ()

Register the user registered filters

public setUniquePrefix (mixed $prefix)

Set a unique prefix to be used as prefix for compiled variables

public getUniquePrefix ()

Return a unique prefix to be used as prefix for compiled variables and contexts

public attributeReader (array $expr)

Resolves attribute reading

public functionCall (array $expr)

Resolves function intermediate code into PHP function calls

public resolveTest (array $test, mixed $left)

Resolves filter intermediate code into a valid PHP expression

final protected resolveFilter (array $filter, mixed $left)

Resolves filter intermediate code into PHP function calls

final public expression (array $expr)

Resolves an expression node in an AST volt tree

final protected string | array _statementListOrExtends (array $statements)

Compiles a block of statements

public compileForeach (array $statement, [mixed $extendsMode])

Compiles a “foreach” intermediate code representation into plain PHP code

public compileForElse ()

Generates a ‘forelse’ PHP code

public compileIf (array $statement, [mixed $extendsMode])

Compiles a ‘if’ statement returning PHP code

public compileElseIf (array $statement)

Compiles a “elseif” statement returning PHP code

public compileCache (array $statement, [mixed $extendsMode])

Compiles a “cache” statement returning PHP code

public compileSet (array $statement)

Compiles a “set” statement returning PHP code

public compileDo (array $statement)

Compiles a “do” statement returning PHP code

public compileReturn (array $statement)

Compiles a “return” statement returning PHP code

public compileAutoEscape (array $statement, mixed $extendsMode)

Compiles a “autoescape” statement returning PHP code

public string compileEcho (array $statement)

Compiles a ‘{{‘ ‘}}’ statement returning PHP code

public compileInclude (array $statement)

Compiles a ‘include’ statement returning PHP code

public compileMacro (array $statement, mixed $extendsMode)

Compiles macros

public string compileCall (array $statement, boolean $extendsMode)

Compiles calls to macros

final protected _statementList (array $statements, [mixed $extendsMode])

Traverses a statement list compiling each of its nodes

protected _compileSource (mixed $viewCode, [mixed $extendsMode])

Compiles a Volt source code returning a PHP plain version

public compileString (mixed $viewCode, [mixed $extendsMode])

Compiles a template into a string

<?php

 echo $compiler->compileString('{{ "hello world" }}');

public string | array compileFile (string $path, string $compiledPath, [boolean $extendsMode])

Compiles a template into a file forcing the destination path

<?php

$compiler->compile('views/layouts/main.volt', 'views/layouts/main.volt.php');

public compile (mixed $templatePath, [mixed $extendsMode])

Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled

<?php

$compiler->compile('views/layouts/main.volt');
require $compiler->getCompiledTemplatePath();

public getTemplatePath ()

Returns the path that is currently being compiled

public getCompiledTemplatePath ()

Returns the path to the last compiled template

public array parse (string $viewCode)

Parses a Volt template returning its intermediate representation

<?php

print_r($compiler->parse('{{ 3 + 2 }}'));

protected getFinalPath (mixed $path)

Gets the final path with VIEW

Class Phalcon\Mvc\View\Engine\Volt\Exception

extends class Phalcon\Mvc\View\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\View\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Mvc\View\Simple

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ViewBaseInterface

Source on GitHub

This component allows to render views without hierarchical levels

<?php

 use Phalcon\Mvc\View\Simple as View;

 $view = new View();

 // Render a view
 echo $view->render('templates/my-view', ['some' => $param]);

 // Or with filename with extension
 echo $view->render('templates/my-view.volt', ['parameter' => $here]);
Methods

public getRegisteredEngines ()

public __construct ([array $options])

Phalcon\Mvc\View\Simple constructor

public setViewsDir (mixed $viewsDir)

Sets views directory. Depending of your platform, always add a trailing slash or backslash

public getViewsDir ()

Gets views directory

public registerEngines (array $engines)

Register templating engines

<?php

 $this->view->registerEngines([
  '.phtml' => 'Phalcon\Mvc\View\Engine\Php',
  '.volt'  => 'Phalcon\Mvc\View\Engine\Volt',
  '.mhtml' => 'MyCustomEngine'
 ]);

protected array _loadTemplateEngines ()

Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php

final protected _internalRender (string $path, array $params)

Tries to render the view with every engine registered in the component

public render (string $path, [array $params])

Renders a view

public partial (mixed $partialPath, [mixed $params])

Renders a partial view

<?php

    // Show a partial inside another view
    $this->partial('shared/footer');
<?php

    // Show a partial inside another view with parameters
    $this->partial('shared/footer', ['content' => $html]);

public setCacheOptions (array $options)

Sets the cache options

public array getCacheOptions ()

Returns the cache options

protected _createCache ()

Create a Phalcon\Cache based on the internal cache options

public getCache ()

Returns the cache instance used to cache

public cache ([mixed $options])

Cache the actual view render to certain level

<?php

  $this->view->cache(['key' => 'my-key', 'lifetime' => 86400]);

public setParamToView (mixed $key, mixed $value)

Adds parameters to views (alias of setVar)

<?php

$this->view->setParamToView('products', $products);

public setVars (array $params, [mixed $merge])

Set all the render params

<?php

$this->view->setVars(['products' => $products]);

public setVar (mixed $key, mixed $value)

Set a single view parameter

<?php

$this->view->setVar('products', $products);

public getVar (mixed $key)

Returns a parameter previously set in the view

public array getParamsToView ()

Returns parameters to views

public setContent (mixed $content)

Externally sets the view content

<?php

$this->view->setContent("<h1>hello</h1>");

public getContent ()

Returns cached output from another view stage

public string getActiveRenderPath ()

Returns the path of the view that is currently rendered

public __set (mixed $key, mixed $value)

Magic method to pass variables to the views

<?php

$this->view->products = $products;

public __get (mixed $key)

Magic method to retrieve a variable passed to the view

<?php

echo $this->view->products;

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

Abstract class Phalcon\Paginator\Adapter

Source on GitHub

Methods

public setCurrentPage (mixed $page)

Set the current page number

public setLimit (mixed $limitRows)

Set current rows limit

public getLimit ()

Get current rows limit

Class Phalcon\Paginator\Adapter\Model

extends abstract class Phalcon\Paginator\Adapter

implements Phalcon\Paginator\AdapterInterface

Source on GitHub

This adapter allows to paginate data using a Phalcon\Mvc\Model resultset as a base.

<?php

 use Phalcon\Paginator\Adapter\Model;

 $paginator = new Model(
     [
         'data'  => Robots::find(),
         'limit' => 25,
         'page'  => $currentPage
     ]
 );

 $paginate = $paginator->getPaginate();
Methods

public __construct (array $config)

Phalcon\Paginator\Adapter\Model constructor

public getPaginate ()

Returns a slice of the resultset to show in the pagination

public setCurrentPage (mixed $page) inherited from Phalcon\Paginator\Adapter

Set the current page number

public setLimit (mixed $limitRows) inherited from Phalcon\Paginator\Adapter

Set current rows limit

public getLimit () inherited from Phalcon\Paginator\Adapter

Get current rows limit

Class Phalcon\Paginator\Adapter\NativeArray

extends abstract class Phalcon\Paginator\Adapter

implements Phalcon\Paginator\AdapterInterface

Source on GitHub

Pagination using a PHP array as source of data

<?php

 use Phalcon\Paginator\Adapter\NativeArray;

 $paginator = new NativeArray(
     [
         'data'  => array(
             ['id' => 1, 'name' => 'Artichoke'],
             ['id' => 2, 'name' => 'Carrots'],
             ['id' => 3, 'name' => 'Beet'],
             ['id' => 4, 'name' => 'Lettuce'],
             ['id' => 5, 'name' => '']
         ],
         'limit' => 2,
         'page'  => $currentPage,
     ]
 );
Methods

public __construct (array $config)

Phalcon\Paginator\Adapter\NativeArray constructor

public getPaginate ()

Returns a slice of the resultset to show in the pagination

public setCurrentPage (mixed $page) inherited from Phalcon\Paginator\Adapter

Set the current page number

public setLimit (mixed $limitRows) inherited from Phalcon\Paginator\Adapter

Set current rows limit

public getLimit () inherited from Phalcon\Paginator\Adapter

Get current rows limit

Class Phalcon\Paginator\Adapter\QueryBuilder

extends abstract class Phalcon\Paginator\Adapter

implements Phalcon\Paginator\AdapterInterface

Source on GitHub

Pagination using a PHQL query builder as source of data

<?php

 use Phalcon\Paginator\Adapter\QueryBuilder;

 $builder = $this->modelsManager->createBuilder()
                 ->columns('id, name')
                 ->from('Robots')
                 ->orderBy('name');

 $paginator = new QueryBuilder(
     [
         'builder' => $builder,
         'limit'   => 20,
         'page'    => 1,
     ]
 );
Methods

public __construct (array $config)

public getCurrentPage ()

Get the current page number

public setQueryBuilder (Phalcon\Mvc\Model\Query\Builder $builder)

Set query builder object

public getQueryBuilder ()

Get query builder object

public getPaginate ()

Returns a slice of the resultset to show in the pagination

public setCurrentPage (mixed $page) inherited from Phalcon\Paginator\Adapter

Set the current page number

public setLimit (mixed $limitRows) inherited from Phalcon\Paginator\Adapter

Set current rows limit

public getLimit () inherited from Phalcon\Paginator\Adapter

Get current rows limit

Class Phalcon\Paginator\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Queue\Beanstalk

Source on GitHub

Class to access the beanstalk queue service. Partially implements the protocol version 1.2

<?php

 use Phalcon\Queue\Beanstalk;

 $queue = new Beanstalk([
     'host'       => '127.0.0.1',
     'port'       => 11300,
     'persistent' => true,
 ]);
Constants

integer DEFAULT_DELAY

integer DEFAULT_PRIORITY

integer DEFAULT_TTR

string DEFAULT_TUBE

string DEFAULT_HOST

integer DEFAULT_PORT

Methods

public __construct ([array $options])

public connect ()

Makes a connection to the Beanstalkd server

public put (mixed $data, [array $options])

Puts a job on the queue using specified tube.

public reserve ([mixed $timeout])

Reserves/locks a ready job from the specified tube.

public choose (mixed $tube)

Change the active tube. By default the tube is “default”.

public watch (mixed $tube)

The watch command adds the named tube to the watch list for the current connection.

public ignore (mixed $tube)

It removes the named tube from the watch list for the current connection.

public pauseTube (mixed $tube, mixed $delay)

Can delay any new job being reserved for a given time.

public kick (mixed $bound)

The kick command applies only to the currently used tube.

public stats ()

Gives statistical information about the system as a whole.

public statsTube (mixed $tube)

Gives statistical information about the specified tube if it exists.

public listTubes ()

Returns a list of all existing tubes.

public listTubeUsed ()

Returns the tube currently being used by the client.

public listTubesWatched ()

Returns a list tubes currently being watched by the client.

public peekReady ()

Inspect the next ready job.

public peekBuried ()

Return the next job in the list of buried jobs.

public peekDelayed ()

Return the next job in the list of buried jobs.

public jobPeek (mixed $id)

The peek commands let the client inspect a job in the system.

final public readStatus ()

Reads the latest status from the Beanstalkd server

final public readYaml ()

Fetch a YAML payload from the Beanstalkd server

public read ([mixed $length])

Reads a packet from the socket. Prior to reading from the socket will check for availability of the connection.

protected write (mixed $data)

Writes data to the socket. Performs a connection if none is available

public disconnect ()

Closes the connection to the beanstalk server.

public quit ()

Simply closes the connection.

Class Phalcon\Queue\Beanstalk\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Queue\Beanstalk\Job

Source on GitHub

Represents a job in a beanstalk queue

Methods

public getId ()

public getBody ()

public __construct (Phalcon\Queue\Beanstalk $queue, mixed $id, mixed $body)

public delete ()

Removes a job from the server entirely

public release ([mixed $priority], [mixed $delay])

The release command puts a reserved job back into the ready queue (and marks its state as “ready”) to be run by any client. It is normally used when the job fails because of a transitory error.

public bury ([mixed $priority])

The bury command puts a job into the “buried” state. Buried jobs are put into a FIFO linked list and will not be touched by the server again until a client kicks them with the “kick” command.

public touch ()

The touch command allows a worker to request more time to work on a job. This is useful for jobs that potentially take a long time, but you still want the benefits of a TTR pulling a job away from an unresponsive worker. A worker may periodically tell the server that it’s still alive and processing a job (e.g. it may do this on DEADLINE_SOON). The command postpones the auto release of a reserved job until TTR seconds from when the command is issued.

public kick ()

Move the job to the ready queue if it is delayed or buried.

public stats ()

Gives statistical information about the specified job if it exists.

public __wakeup ()

Checks if the job has been modified after unserializing the object

Final class Phalcon\Registry

implements ArrayAccess, Countable, Iterator, Traversable

Source on GitHub

A registry is a container for storing objects and values in the application space. By storing the value in a registry, the same object is always available throughout your application.

  <?php

      $registry = new \Phalcon\Registry();

      // Set value
      $registry->something = 'something';
      // or
      $registry['something'] = 'something';

      // Get value
      $value = $registry->something;
      // or
      $value = $registry['something'];

      // Check if the key exists
      $exists = isset($registry->something);
      // or
      $exists = isset($registry['something']);

      // Unset
      unset($registry->something);
      // or
      unset($registry['something']);

In addition to ArrayAccess, Phalcon\\Registry also implements Countable (count($registry) will return the number of elements in the registry), Serializable and Iterator (you can iterate over the registry using a foreach loop) interfaces. For PHP 5.4 and higher, JsonSerializable interface is implemented.  Phalcon\\Registry is very fast (it is typically faster than any userspace implementation of the registry); however, this comes at a price: Phalcon\\Registry is a final class and cannot be inherited from.  Though Phalcon\\Registry exposes methods like __get(), offsetGet(), count() etc, it is not recommended to invoke them manually (these methods exist mainly to match the interfaces the registry implements): $registry->__get('property') is several times slower than $registry->property.  Internally all the magic methods (and interfaces except JsonSerializable) are implemented using object handlers or similar techniques: this allows to bypass relatively slow method calls.
Methods

final public __construct ()

Registry constructor

final public offsetExists (mixed $offset)

Checks if the element is present in the registry

final public offsetGet (mixed $offset)

Returns an index in the registry

final public offsetSet (mixed $offset, mixed $value)

Sets an element in the registry

final public offsetUnset (mixed $offset)

Unsets an element in the registry

final public count ()

Checks how many elements are in the register

final public next ()

Moves cursor to next row in the registry

final public key ()

Gets pointer number of active row in the registry

final public rewind ()

Rewinds the registry cursor to its beginning

public valid ()

Checks if the iterator is valid

public current ()

Obtains the current value in the internal iterator

final public __set (mixed $key, mixed $value)

Sets an element in the registry

final public __get (mixed $key)

Returns an index in the registry

final public __isset (mixed $key)

...

final public __unset (mixed $key)

...

Class Phalcon\Security

implements Phalcon\Di\InjectionAwareInterface

Source on GitHub

This component provides a set of functions to improve the security in Phalcon applications

<?php

$login = $this->request->getPost('login');
$password = $this->request->getPost('password');

$user = Users::findFirstByLogin($login);
if ($user) {
    if ($this->security->checkHash($password, $user->password)) {
            //The password is valid
    }
}
Constants

integer CRYPT_DEFAULT

integer CRYPT_STD_DES

integer CRYPT_EXT_DES

integer CRYPT_MD5

integer CRYPT_BLOWFISH

integer CRYPT_BLOWFISH_A

integer CRYPT_BLOWFISH_X

integer CRYPT_BLOWFISH_Y

integer CRYPT_SHA256

integer CRYPT_SHA512

Methods

public setWorkFactor (mixed $workFactor)

...

public getWorkFactor ()

...

public __construct ()

Phalcon\Security constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector

public getDI ()

Returns the internal dependency injector

public setRandomBytes (mixed $randomBytes)

Sets a number of bytes to be generated by the openssl pseudo random generator

public getRandomBytes ()

Returns a number of bytes to be generated by the openssl pseudo random generator

public getRandom ()

Returns a secure random number generator instance

public getSaltBytes ([mixed $numberBytes])

Generate a >22-length pseudo random string to be used as salt for passwords

public hash (mixed $password, [mixed $workFactor])

Creates a password hash using bcrypt with a pseudo random salt

public checkHash (mixed $password, mixed $passwordHash, [mixed $maxPassLength])

Checks a plain text password and its hash version to check if the password matches

public isLegacyHash (mixed $passwordHash)

Checks if a password hash is a valid bcrypt’s hash

public getTokenKey ()

Generates a pseudo random token key to be used as input’s name in a CSRF check

public getToken ()

Generates a pseudo random token value to be used as input’s value in a CSRF check

public checkToken ([mixed $tokenKey], [mixed $tokenValue], [mixed $destroyIfValid])

Check if the CSRF token sent in the request is the same that the current in session

public getSessionToken ()

Returns the value of the CSRF token in session

public destroyToken ()

Removes the value of the CSRF token and key from session

public computeHmac (mixed $data, mixed $key, mixed $algo, [mixed $raw])

Computes a HMAC

public setDefaultHash (mixed $defaultHash)

Sets the default hash

public getDefaultHash ()

Returns the default hash

public hasLibreSsl ()

Testing for LibreSSL

public getSslVersionNumber ()

Getting OpenSSL or LibreSSL version Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.

<?php

 if ($security->getSslVersionNumber() >= 20105) {
     // ...
 }
Class Phalcon\Security\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Security\Random

Source on GitHub

Secure random number generator class. Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc. It supports following secure random number generators: - random_bytes (PHP 7) - libsodium - openssl, libressl - /dev/urandom Phalcon\Security\Random could be mainly useful for: - Key generation (e.g. generation of complicated keys) - Generating random passwords for new user accounts - Encryption systems

  <?php

    $random = new \Phalcon\Security\Random();

    // Random binary string
    $bytes = $random->bytes();

    // Random hex string
    echo $random->hex(10); // a29f470508d5ccb8e289
    echo $random->hex(10); // 533c2f08d5eee750e64a
    echo $random->hex(11); // f362ef96cb9ffef150c9cd
    echo $random->hex(12); // 95469d667475125208be45c4
    echo $random->hex(13); // 05475e8af4a34f8f743ab48761

    // Random base64 string
    echo $random->base64(12); // XfIN81jGGuKkcE1E
    echo $random->base64(12); // 3rcq39QzGK9fUqh8
    echo $random->base64();   // DRcfbngL/iOo9hGGvy1TcQ==
    echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg==

    // Random URL-safe base64 string
    echo $random->base64Safe();           // PcV6jGbJ6vfVw7hfKIFDGA
    echo $random->base64Safe();           // GD8JojhzSTrqX7Q8J6uug
    echo $random->base64Safe(8);          // mGyy0evy3ok
    echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ==

    // Random UUID
    echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235
    echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2
    echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9
    echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d

    // Random number between 0 and $len
    echo $random->number(256); // 84
    echo $random->number(256); // 79
    echo $random->number(100); // 29
    echo $random->number(300); // 40

    // Random base58 string
    echo $random->base58();   // 4kUgL2pdQMSCQtjE
    echo $random->base58();   // Umjxqf7ZPwh765yR
    echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9
    echo $random->base58(7);  // 774SJD3vgP

This class partially borrows SecureRandom library from Ruby
Methods

public bytes ([mixed $len])

Generates a random binary string The Random::bytes method returns a string and accepts as input an int representing the length in bytes to be returned. If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: “x00” - “xFF”.

<?php

  $random = new \Phalcon\Security\Random();

  $bytes = $random->bytes();
  var_dump(bin2hex($bytes));
  // possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee"

public hex ([mixed $len])

Generates a random hex string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len.

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->hex(10); // a29f470508d5ccb8e289

public base58 ([mixed $n])

Generates a random base58 string If $len is not specified, 16 is assumed. It may be larger in future. The result may contain alphanumeric characters except 0, O, I and l. It is similar to Base64 but has been modified to avoid both non-alphanumeric characters and letters which might look ambiguous when printed.

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->base58(); // 4kUgL2pdQMSCQtjE

public base64 ([mixed $len])

Generates a random base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. Size formula: 4 *( $len / 3) and this need to be rounded up to a multiple of 4.

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->base64(12); // 3rcq39QzGK9fUqh8

public base64Safe ([mixed $len], [mixed $padding])

Generates a random URL-safe base64 string If $len is not specified, 16 is assumed. It may be larger in future. The length of the result string is usually greater of $len. By default, padding is not generated because “=” may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, “-” and “_”. “=” is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64.

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug

public uuid ()

Generates a v4 random UUID (Universally Unique IDentifier) The version 4 UUID is purely random (except the version). It doesn’t contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID. This algorithm sets the version number (4 bits) as well as two reserved bits. All other bits (the remaining 122 bits) are set using a random or pseudorandom data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22

public number (mixed $len)

Generates a random number between 0 and $len Returns an integer: 0 <= result <= $len.

<?php

  $random = new \Phalcon\Security\Random();

  echo $random->number(16); // 8
Abstract class Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Source on GitHub

Base class for Phalcon\Session adapters

Constants

integer SESSION_ACTIVE

integer SESSION_NONE

integer SESSION_DISABLED

Methods

public __construct ([array $options])

Phalcon\Session\Adapter constructor

public start ()

Starts the session (if headers are already sent the session will not be started)

public setOptions (array $options)

Sets session’s options

<?php

$session->setOptions(['uniqueId' => 'my-private-app']);

public getOptions ()

Get internal options

public setName (mixed $name)

Set session name

public getName ()

Get session name

public regenerateId ([mixed $deleteOldSession])

public get (mixed $index, [mixed $defaultValue], [mixed $remove])

Gets a session variable from an application context

<?php

$session->get('auth', 'yes');

public set (mixed $index, mixed $value)

Sets a session variable in an application context

<?php

$session->set('auth', 'yes');

public has (mixed $index)

Check whether a session variable is set in an application context

<?php

var_dump($session->has('auth'));

public remove (mixed $index)

Removes a session variable from an application context

<?php

$session->remove('auth');

public getId ()

Returns active session id

<?php

echo $session->getId();

public setId (mixed $id)

Set the current session id

<?php

$session->setId($id);

public isStarted ()

Check whether the session has been started

<?php

var_dump($session->isStarted());

public destroy ([mixed $removeData])

Destroys the active session

<?php

var_dump($session->destroy());
var_dump($session->destroy(true));

public status ()

Returns the status of the current session.

<?php

var_dump($session->status());

  if ($session->status() !== $session::SESSION_ACTIVE) {
      $session->start();
  }

public __get (mixed $index)

Alias: Gets a session variable from an application context

public __set (mixed $index, mixed $value)

Alias: Sets a session variable in an application context

public __isset (mixed $index)

Alias: Check whether a session variable is set in an application context

public __unset (mixed $index)

Alias: Removes a session variable from an application context

public __destruct ()

...

Class Phalcon\Session\Adapter\Files

extends abstract class Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Source on GitHub

Constants

integer SESSION_ACTIVE

integer SESSION_NONE

integer SESSION_DISABLED

Methods

public __construct ([array $options]) inherited from Phalcon\Session\Adapter

Phalcon\Session\Adapter constructor

public start () inherited from Phalcon\Session\Adapter

Starts the session (if headers are already sent the session will not be started)

public setOptions (array $options) inherited from Phalcon\Session\Adapter

Sets session’s options

<?php

$session->setOptions(['uniqueId' => 'my-private-app']);

public getOptions () inherited from Phalcon\Session\Adapter

Get internal options

public setName (mixed $name) inherited from Phalcon\Session\Adapter

Set session name

public getName () inherited from Phalcon\Session\Adapter

Get session name

public regenerateId ([mixed $deleteOldSession]) inherited from Phalcon\Session\Adapter

public get (mixed $index, [mixed $defaultValue], [mixed $remove]) inherited from Phalcon\Session\Adapter

Gets a session variable from an application context

<?php

$session->get('auth', 'yes');

public set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Sets a session variable in an application context

<?php

$session->set('auth', 'yes');

public has (mixed $index) inherited from Phalcon\Session\Adapter

Check whether a session variable is set in an application context

<?php

var_dump($session->has('auth'));

public remove (mixed $index) inherited from Phalcon\Session\Adapter

Removes a session variable from an application context

<?php

$session->remove('auth');

public getId () inherited from Phalcon\Session\Adapter

Returns active session id

<?php

echo $session->getId();

public setId (mixed $id) inherited from Phalcon\Session\Adapter

Set the current session id

<?php

$session->setId($id);

public isStarted () inherited from Phalcon\Session\Adapter

Check whether the session has been started

<?php

var_dump($session->isStarted());

public destroy ([mixed $removeData]) inherited from Phalcon\Session\Adapter

Destroys the active session

<?php

var_dump($session->destroy());
var_dump($session->destroy(true));

public status () inherited from Phalcon\Session\Adapter

Returns the status of the current session.

<?php

var_dump($session->status());

  if ($session->status() !== $session::SESSION_ACTIVE) {
      $session->start();
  }

public __get (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Gets a session variable from an application context

public __set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Alias: Sets a session variable in an application context

public __isset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Check whether a session variable is set in an application context

public __unset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Removes a session variable from an application context

public __destruct () inherited from Phalcon\Session\Adapter

...

Class Phalcon\Session\Adapter\Libmemcached

extends abstract class Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Source on GitHub

This adapter store sessions in libmemcached

<?php

 use Phalcon\Session\Adapter\Libmemcached;

 $session = new Libmemcached([
     'servers' => [
         ['host' => 'localhost', 'port' => 11211, 'weight' => 1],
     ],
     'client' => [
         \Memcached::OPT_HASH       => \Memcached::HASH_MD5,
         \Memcached::OPT_PREFIX_KEY => 'prefix.',
     ],
     'lifetime' => 3600,
     'prefix'   => 'my_'
 ]);

 $session->start();

 $session->set('var', 'some-value');

 echo $session->get('var');
Constants

integer SESSION_ACTIVE

integer SESSION_NONE

integer SESSION_DISABLED

Methods

public getLibmemcached ()

...

public getLifetime ()

...

public __construct (array $options)

Phalcon\Session\Adapter\Libmemcached constructor

public open ()

...

public close ()

...

public read (mixed $sessionId)

public write (mixed $sessionId, mixed $data)

public destroy ([mixed $sessionId])

public gc ()

public start () inherited from Phalcon\Session\Adapter

Starts the session (if headers are already sent the session will not be started)

public setOptions (array $options) inherited from Phalcon\Session\Adapter

Sets session’s options

<?php

$session->setOptions(['uniqueId' => 'my-private-app']);

public getOptions () inherited from Phalcon\Session\Adapter

Get internal options

public setName (mixed $name) inherited from Phalcon\Session\Adapter

Set session name

public getName () inherited from Phalcon\Session\Adapter

Get session name

public regenerateId ([mixed $deleteOldSession]) inherited from Phalcon\Session\Adapter

public get (mixed $index, [mixed $defaultValue], [mixed $remove]) inherited from Phalcon\Session\Adapter

Gets a session variable from an application context

<?php

$session->get('auth', 'yes');

public set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Sets a session variable in an application context

<?php

$session->set('auth', 'yes');

public has (mixed $index) inherited from Phalcon\Session\Adapter

Check whether a session variable is set in an application context

<?php

var_dump($session->has('auth'));

public remove (mixed $index) inherited from Phalcon\Session\Adapter

Removes a session variable from an application context

<?php

$session->remove('auth');

public getId () inherited from Phalcon\Session\Adapter

Returns active session id

<?php

echo $session->getId();

public setId (mixed $id) inherited from Phalcon\Session\Adapter

Set the current session id

<?php

$session->setId($id);

public isStarted () inherited from Phalcon\Session\Adapter

Check whether the session has been started

<?php

var_dump($session->isStarted());

public status () inherited from Phalcon\Session\Adapter

Returns the status of the current session.

<?php

var_dump($session->status());

  if ($session->status() !== $session::SESSION_ACTIVE) {
      $session->start();
  }

public __get (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Gets a session variable from an application context

public __set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Alias: Sets a session variable in an application context

public __isset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Check whether a session variable is set in an application context

public __unset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Removes a session variable from an application context

public __destruct () inherited from Phalcon\Session\Adapter

...

Class Phalcon\Session\Adapter\Memcache

extends abstract class Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Source on GitHub

This adapter store sessions in memcache

<?php

 use Phalcon\Session\Adapter\Memcache;

 $session = new Memcache([
     'uniqueId'   => 'my-private-app',
     'host'       => '127.0.0.1',
     'port'       => 11211,
     'persistent' => true,
     'lifetime'   => 3600,
     'prefix'     => 'my_'
 ]);

 $session->start();

 $session->set('var', 'some-value');

 echo $session->get('var');
Constants

integer SESSION_ACTIVE

integer SESSION_NONE

integer SESSION_DISABLED

Methods

public getMemcache ()

...

public getLifetime ()

...

public __construct ([array $options])

Phalcon\Session\Adapter\Memcache constructor

public open ()

...

public close ()

...

public read (mixed $sessionId)

public write (mixed $sessionId, mixed $data)

public destroy ([mixed $sessionId])

public gc ()

public start () inherited from Phalcon\Session\Adapter

Starts the session (if headers are already sent the session will not be started)

public setOptions (array $options) inherited from Phalcon\Session\Adapter

Sets session’s options

<?php

$session->setOptions(['uniqueId' => 'my-private-app']);

public getOptions () inherited from Phalcon\Session\Adapter

Get internal options

public setName (mixed $name) inherited from Phalcon\Session\Adapter

Set session name

public getName () inherited from Phalcon\Session\Adapter

Get session name

public regenerateId ([mixed $deleteOldSession]) inherited from Phalcon\Session\Adapter

public get (mixed $index, [mixed $defaultValue], [mixed $remove]) inherited from Phalcon\Session\Adapter

Gets a session variable from an application context

<?php

$session->get('auth', 'yes');

public set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Sets a session variable in an application context

<?php

$session->set('auth', 'yes');

public has (mixed $index) inherited from Phalcon\Session\Adapter

Check whether a session variable is set in an application context

<?php

var_dump($session->has('auth'));

public remove (mixed $index) inherited from Phalcon\Session\Adapter

Removes a session variable from an application context

<?php

$session->remove('auth');

public getId () inherited from Phalcon\Session\Adapter

Returns active session id

<?php

echo $session->getId();

public setId (mixed $id) inherited from Phalcon\Session\Adapter

Set the current session id

<?php

$session->setId($id);

public isStarted () inherited from Phalcon\Session\Adapter

Check whether the session has been started

<?php

var_dump($session->isStarted());

public status () inherited from Phalcon\Session\Adapter

Returns the status of the current session.

<?php

var_dump($session->status());

  if ($session->status() !== $session::SESSION_ACTIVE) {
      $session->start();
  }

public __get (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Gets a session variable from an application context

public __set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Alias: Sets a session variable in an application context

public __isset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Check whether a session variable is set in an application context

public __unset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Removes a session variable from an application context

public __destruct () inherited from Phalcon\Session\Adapter

...

Class Phalcon\Session\Adapter\Redis

extends abstract class Phalcon\Session\Adapter

implements Phalcon\Session\AdapterInterface

Source on GitHub

This adapter store sessions in Redis

<?php

 use Phalcon\Session\Adapter\Redis;

 $session = new Redis([
     'uniqueId'   => 'my-private-app',
     'host'       => 'localhost',
     'port'       => 6379,
     'auth'       => 'foobared',
     'persistent' => false,
     'lifetime'   => 3600,
     'prefix'     => 'my_'
     'index'      => 1,
 ]);

 $session->start();

 $session->set('var', 'some-value');

 echo $session->get('var');
Constants

integer SESSION_ACTIVE

integer SESSION_NONE

integer SESSION_DISABLED

Methods

public getRedis ()

...

public getLifetime ()

...

public __construct ([array $options])

Phalcon\Session\Adapter\Redis constructor

public open ()

public close ()

public read (mixed $sessionId)

public write (mixed $sessionId, mixed $data)

public destroy ([mixed $sessionId])

public gc ()

public start () inherited from Phalcon\Session\Adapter

Starts the session (if headers are already sent the session will not be started)

public setOptions (array $options) inherited from Phalcon\Session\Adapter

Sets session’s options

<?php

$session->setOptions(['uniqueId' => 'my-private-app']);

public getOptions () inherited from Phalcon\Session\Adapter

Get internal options

public setName (mixed $name) inherited from Phalcon\Session\Adapter

Set session name

public getName () inherited from Phalcon\Session\Adapter

Get session name

public regenerateId ([mixed $deleteOldSession]) inherited from Phalcon\Session\Adapter

public get (mixed $index, [mixed $defaultValue], [mixed $remove]) inherited from Phalcon\Session\Adapter

Gets a session variable from an application context

<?php

$session->get('auth', 'yes');

public set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Sets a session variable in an application context

<?php

$session->set('auth', 'yes');

public has (mixed $index) inherited from Phalcon\Session\Adapter

Check whether a session variable is set in an application context

<?php

var_dump($session->has('auth'));

public remove (mixed $index) inherited from Phalcon\Session\Adapter

Removes a session variable from an application context

<?php

$session->remove('auth');

public getId () inherited from Phalcon\Session\Adapter

Returns active session id

<?php

echo $session->getId();

public setId (mixed $id) inherited from Phalcon\Session\Adapter

Set the current session id

<?php

$session->setId($id);

public isStarted () inherited from Phalcon\Session\Adapter

Check whether the session has been started

<?php

var_dump($session->isStarted());

public status () inherited from Phalcon\Session\Adapter

Returns the status of the current session.

<?php

var_dump($session->status());

  if ($session->status() !== $session::SESSION_ACTIVE) {
      $session->start();
  }

public __get (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Gets a session variable from an application context

public __set (mixed $index, mixed $value) inherited from Phalcon\Session\Adapter

Alias: Sets a session variable in an application context

public __isset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Check whether a session variable is set in an application context

public __unset (mixed $index) inherited from Phalcon\Session\Adapter

Alias: Removes a session variable from an application context

public __destruct () inherited from Phalcon\Session\Adapter

...

Class Phalcon\Session\Bag

implements Phalcon\Di\InjectionAwareInterface, Phalcon\Session\BagInterface, IteratorAggregate, Traversable, ArrayAccess, Countable

Source on GitHub

This component helps to separate session data into “namespaces”. Working by this way you can easily create groups of session variables into the application

<?php

$user = new \Phalcon\Session\Bag('user');
$user->name = "Kimbra Johnson";
$user->age  = 22;
Methods

public __construct (mixed $name)

Phalcon\Session\Bag constructor

public setDI (Phalcon\DiInterface $dependencyInjector)

Sets the DependencyInjector container

public getDI ()

Returns the DependencyInjector container

public initialize ()

Initializes the session bag. This method must not be called directly, the class calls it when its internal data is accessed

public destroy ()

Destroys the session bag

<?php

 $user->destroy();

public set (mixed $property, mixed $value)

Sets a value in the session bag

<?php

 $user->set('name', 'Kimbra');

public __set (mixed $property, mixed $value)

Magic setter to assign values to the session bag

<?php

 $user->name = "Kimbra";

public get (mixed $property, [mixed $defaultValue])

Obtains a value from the session bag optionally setting a default value

<?php

 echo $user->get('name', 'Kimbra');

public __get (mixed $property)

Magic getter to obtain values from the session bag

<?php

 echo $user->name;

public has (mixed $property)

Check whether a property is defined in the internal bag

<?php

 var_dump($user->has('name'));

public __isset (mixed $property)

Magic isset to check whether a property is defined in the bag

<?php

 var_dump(isset($user['name']));

public remove (mixed $property)

Removes a property from the internal bag

<?php

 $user->remove('name');

public __unset (mixed $property)

Magic unset to remove items using the array syntax

<?php

 unset($user['name']);

final public count ()

Return length of bag

<?php

 echo $user->count();

final public getIterator ()

 Returns the bag iterator

final public offsetSet (mixed $property, mixed $value)

...

final public offsetExists (mixed $property)

...

final public offsetUnset (mixed $property)

...

final public offsetGet (mixed $property)

...

Class Phalcon\Session\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Tag

Source on GitHub

Phalcon\Tag is designed to simplify building of HTML tags. It provides a set of helpers to generate HTML in a dynamic way. This component is an abstract class that you can extend to add more helpers.

Constants

integer HTML32

integer HTML401_STRICT

integer HTML401_TRANSITIONAL

integer HTML401_FRAMESET

integer HTML5

integer XHTML10_STRICT

integer XHTML10_TRANSITIONAL

integer XHTML10_FRAMESET

integer XHTML11

integer XHTML20

integer XHTML5

Methods

public static EscaperInterface getEscaper (array $params)

Obtains the ‘escaper’ service if required

public static renderAttributes (mixed $code, array $attributes)

Renders parameters keeping order in their HTML attributes

public static setDI (Phalcon\DiInterface $dependencyInjector)

Sets the dependency injector container.

public static getDI ()

Internally gets the request dispatcher

public static getUrlService ()

Returns a URL service from the default DI

public static getEscaperService ()

Returns an Escaper service from the default DI

public static setAutoescape (mixed $autoescape)

Set autoescape mode in generated html

public static setDefault (string $id, string $value)

Assigns default values to generated tags by helpers

<?php

 // Assigning "peter" to "name" component
 Phalcon\Tag::setDefault("name", "peter");

 // Later in the view
 echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default

public static setDefaults (array $values, [mixed $merge])

Assigns default values to generated tags by helpers

<?php

 // Assigning "peter" to "name" component
 Phalcon\Tag::setDefaults(array("name" => "peter"));

 // Later in the view
 echo Phalcon\Tag::textField("name"); //Will have the value "peter" by default

public static displayTo (string $id, string $value)

Alias of Phalcon\Tag::setDefault

public static boolean hasValue (string $name)

Check if a helper has a default value set using Phalcon\Tag::setDefault or value from _POST

public static mixed getValue (string $name, [array $params])

Every helper calls this function to check whether a component has a predefined value using Phalcon\Tag::setDefault or value from _POST

public static resetInput ()

Resets the request and internal values to avoid those fields will have any default value

public static string linkTo (array | string $parameters, [string $text], [boolean $local])

Builds a HTML A tag using framework conventions

<?php

 echo Phalcon\Tag::linkTo("signup/register", "Register Here!");
 echo Phalcon\Tag::linkTo(array("signup/register", "Register Here!"));
 echo Phalcon\Tag::linkTo(array("signup/register", "Register Here!", "class" => "btn-primary"));
 echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", FALSE);
 echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", FALSE));
 echo Phalcon\Tag::linkTo(array("http://phalconphp.com/", "Phalcon Home", "local" =>FALSE));

final protected static string _inputField (string $type, array $parameters, [boolean $asValue])

Builds generic INPUT tags

final protected static string _inputFieldChecked (string $type, array $parameters)

Builds INPUT tags that implements the checked attribute

public static string colorField (array $parameters)

Builds a HTML input[type=”color”] tag

public static string textField (array $parameters)

Builds a HTML input[type=”text”] tag

<?php

 echo Phalcon\Tag::textField(array("name", "size" => 30));

public static string numericField (array $parameters)

Builds a HTML input[type=”number”] tag

<?php

 echo Phalcon\Tag::numericField(array("price", "min" => "1", "max" => "5"));

public static string rangeField (array $parameters)

Builds a HTML input[type=”range”] tag

public static string emailField (array $parameters)

Builds a HTML input[type=”email”] tag

<?php

 echo Phalcon\Tag::emailField("email");

public static string dateField (array $parameters)

Builds a HTML input[type=”date”] tag

<?php

 echo Phalcon\Tag::dateField(array("born", "value" => "14-12-1980"))

public static string dateTimeField (array $parameters)

Builds a HTML input[type=”datetime”] tag

public static string dateTimeLocalField (array $parameters)

Builds a HTML input[type=”datetime-local”] tag

public static string monthField (array $parameters)

Builds a HTML input[type=”month”] tag

public static string timeField (array $parameters)

Builds a HTML input[type=”time”] tag

public static string weekField (array $parameters)

Builds a HTML input[type=”week”] tag

public static string passwordField (array $parameters)

Builds a HTML input[type=”password”] tag

<?php

 echo Phalcon\Tag::passwordField(array("name", "size" => 30));

public static string hiddenField (array $parameters)

Builds a HTML input[type=”hidden”] tag

<?php

 echo Phalcon\Tag::hiddenField(array("name", "value" => "mike"));

public static string fileField (array $parameters)

Builds a HTML input[type=”file”] tag

<?php

 echo Phalcon\Tag::fileField("file");

public static string searchField (array $parameters)

Builds a HTML input[type=”search”] tag

public static string telField (array $parameters)

Builds a HTML input[type=”tel”] tag

public static string urlField (array $parameters)

Builds a HTML input[type=”url”] tag

public static string checkField (array $parameters)

Builds a HTML input[type=”check”] tag

<?php

 echo Phalcon\Tag::checkField(array("terms", "value" => "Y"));

Volt syntax:

<?php

 {{ check_field("terms") }}

public static string radioField (array $parameters)

Builds a HTML input[type=”radio”] tag

<?php

 echo Phalcon\Tag::radioField(array("weather", "value" => "hot"))

Volt syntax:

<?php

 {{ radio_field("Save") }}

public static string imageInput (array $parameters)

Builds a HTML input[type=”image”] tag

<?php

 echo Phalcon\Tag::imageInput(array("src" => "/img/button.png"));

Volt syntax:

<?php

 {{ image_input("src": "/img/button.png") }}

public static string submitButton (array $parameters)

Builds a HTML input[type=”submit”] tag

<?php

 echo Phalcon\Tag::submitButton("Save")

Volt syntax:

<?php

 {{ submit_button("Save") }}

public static string selectStatic (array $parameters, [array $data])

Builds a HTML SELECT tag using a PHP array for options

<?php

 echo Phalcon\Tag::selectStatic("status", array("A" => "Active", "I" => "Inactive"))

public static string select (array $parameters, [array $data])

Builds a HTML SELECT tag using a Phalcon\Mvc\Model resultset as options

<?php

 echo Phalcon\Tag::select([
     "robotId",
     Robots::find("type = "mechanical""),
     "using" => ["id", "name"]
 ]);

Volt syntax:

<?php

 {{ select("robotId", robots, "using": ["id", "name"]) }}

public static string textArea (array $parameters)

Builds a HTML TEXTAREA tag

<?php

 echo Phalcon\Tag::textArea(array("comments", "cols" => 10, "rows" => 4))

Volt syntax:

<?php

 {{ text_area("comments", "cols": 10, "rows": 4) }}

public static string form (array $parameters)

Builds a HTML FORM tag

<?php

 echo Phalcon\Tag::form("posts/save");
 echo Phalcon\Tag::form(array("posts/save", "method" => "post"));

Volt syntax:

<?php

 {{ form("posts/save") }}
 {{ form("posts/save", "method": "post") }}

public static endForm ()

Builds a HTML close FORM tag

public static setTitle (mixed $title)

Set the title of view content

<?php

 Phalcon\Tag::setTitle("Welcome to my Page");

public static setTitleSeparator (mixed $titleSeparator)

Set the title separator of view content

<?php

 Phalcon\Tag::setTitleSeparator("-");

public static appendTitle (mixed $title)

Appends a text to current document title

public static prependTitle (mixed $title)

Prepends a text to current document title

public static getTitle ([mixed $tags])

Gets the current document title. The title will be automatically escaped.

<?php

 echo Phalcon\Tag::getTitle();
<?php

 {{ get_title() }}

public static getTitleSeparator ()

Gets the current document title separator

<?php

 echo Phalcon\Tag::getTitleSeparator();
<?php

 {{ get_title_separator() }}

public static string stylesheetLink ([array $parameters], [boolean $local])

Builds a LINK[rel=”stylesheet”] tag

<?php

 echo Phalcon\Tag::stylesheetLink("http://fonts.googleapis.com/css?family=Rosario", false);
 echo Phalcon\Tag::stylesheetLink("css/style.css");

Volt Syntax:

<?php

 {{ stylesheet_link("http://fonts.googleapis.com/css?family=Rosario", false) }}
 {{ stylesheet_link("css/style.css") }}

public static string javascriptInclude ([array $parameters], [boolean $local])

Builds a SCRIPT[type=”javascript”] tag

<?php

 echo Phalcon\Tag::javascriptInclude("http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", false);
 echo Phalcon\Tag::javascriptInclude("javascript/jquery.js");

Volt syntax:

<?php

 {{ javascript_include("http://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js", false) }}
 {{ javascript_include("javascript/jquery.js") }}

public static string image ([array $parameters], [boolean $local])

Builds HTML IMG tags

<?php

 echo Phalcon\Tag::image("img/bg.png");
 echo Phalcon\Tag::image(array("img/photo.jpg", "alt" => "Some Photo"));

Volt Syntax:

<?php

 {{ image("img/bg.png") }}
 {{ image("img/photo.jpg", "alt": "Some Photo") }}
 {{ image("http://static.mywebsite.com/img/bg.png", false) }}

public static friendlyTitle (mixed $text, [mixed $separator], [mixed $lowercase], [mixed $replace])

Converts texts into URL-friendly titles

<?php

 echo Phalcon\Tag::friendlyTitle("These are big important news", "-")

public static setDocType (mixed $doctype)

Set the document type of content

public static getDocType ()

Get the document type declaration of content

public static tagHtml (mixed $tagName, [mixed $parameters], [mixed $selfClose], [mixed $onlyStart], [mixed $useEol])

Builds a HTML tag

<?php

 echo Phalcon\Tag::tagHtml(name, parameters, selfClose, onlyStart, eol);

public static tagHtmlClose (mixed $tagName, [mixed $useEol])

Builds a HTML tag closing tag

<?php

 echo Phalcon\Tag::tagHtmlClose("script", true)
Class Phalcon\Tag\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Abstract class Phalcon\Tag\Select

Source on GitHub

Generates a SELECT html tag using a static array of values or a Phalcon\Mvc\Model resultset

Methods

public static selectField (array $parameters, [array $data])

Generates a SELECT tag

private static _optionsFromResultset (Phalcon\Mvc\Model\Resultset $resultset, array $using, mixed $value, string $closeOption)

Generate the OPTION tags based on a resultset

private static _optionsFromArray (array $data, mixed $value, string $closeOption)

Generate the OPTION tags based on an array

Abstract class Phalcon\Text

Source on GitHub

Provides utilities to work with texts

Constants

integer RANDOM_ALNUM

integer RANDOM_ALPHA

integer RANDOM_HEXDEC

integer RANDOM_NUMERIC

integer RANDOM_NOZERO

Methods

public static camelize (mixed $str, [mixed $delimiter])

Converts strings to camelize style

<?php

    echo Phalcon\Text::camelize('coco_bongo'); // CocoBongo
    echo Phalcon\Text::camelize('co_co-bon_go', '-'); // Co_coBon_go
    echo Phalcon\Text::camelize('co_co-bon_go', '_-'); // CoCoBonGo

public static uncamelize (mixed $str, [mixed $delimiter])

Uncamelize strings which are camelized

<?php

    echo Phalcon\Text::uncamelize('CocoBongo'); // coco_bongo
    echo Phalcon\Text::uncamelize('CocoBongo', '-'); // coco-bongo

public static increment (mixed $str, [mixed $separator])

Adds a number to a string or increment that number if it already is defined

<?php

    echo Phalcon\Text::increment("a"); // "a_1"
    echo Phalcon\Text::increment("a_1"); // "a_2"

public static random ([mixed $type], [mixed $length])

Generates a random string based on the given type. Type is one of the RANDOM_* constants

<?php

    echo Phalcon\Text::random(Phalcon\Text::RANDOM_ALNUM); //"aloiwkqz"

public static startsWith (mixed $str, mixed $start, [mixed $ignoreCase])

Check if a string starts with a given string

<?php

    echo Phalcon\Text::startsWith("Hello", "He"); // true
    echo Phalcon\Text::startsWith("Hello", "he", false); // false
    echo Phalcon\Text::startsWith("Hello", "he"); // true

public static endsWith (mixed $str, mixed $end, [mixed $ignoreCase])

Check if a string ends with a given string

<?php

    echo Phalcon\Text::endsWith("Hello", "llo"); // true
    echo Phalcon\Text::endsWith("Hello", "LLO", false); // false
    echo Phalcon\Text::endsWith("Hello", "LLO"); // true

public static lower (mixed $str, [mixed $encoding])

Lowercases a string, this function makes use of the mbstring extension if available

<?php

    echo Phalcon\Text::lower("HELLO"); // hello

public static upper (mixed $str, [mixed $encoding])

Uppercases a string, this function makes use of the mbstring extension if available

<?php

    echo Phalcon\Text::upper("hello"); // HELLO

public static reduceSlashes (mixed $str)

Reduces multiple slashes in a string to single slashes

<?php

    echo Phalcon\Text::reduceSlashes("foo//bar/baz"); // foo/bar/baz
    echo Phalcon\Text::reduceSlashes("http://foo.bar///baz/buz"); // http://foo.bar/baz/buz

public static concat ()

Concatenates strings using the separator only once without duplication in places concatenation

<?php

    $str = Phalcon\Text::concat("/", "/tmp/", "/folder_1/", "/folder_2", "folder_3/");
    echo $str; // /tmp/folder_1/folder_2/folder_3/

public static dynamic (mixed $text, [mixed $leftDelimiter], [mixed $rightDelimiter], [mixed $separator])

Generates random text in accordance with the template

<?php

    echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hi my name is a Bob
    echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hi my name is a Jon
    echo Phalcon\Text::dynamic("{Hi|Hello}, my name is a {Bob|Mark|Jon}!"); // Hello my name is a Bob
    echo Phalcon\Text::dynamic("[Hi/Hello], my name is a [Zyxep/Mark]!", '[', ']', '/'); // Hello my name is a Zyxep

public static underscore (mixed $text)

Makes a phrase underscored instead of spaced

<?php

   echo Phalcon\Text::underscore('look behind'); // 'look_behind'
   echo Phalcon\Text::underscore('Awesome Phalcon'); // 'Awesome_Phalcon'

public static humanize (mixed $text)

Makes an underscored or dashed phrase human-readable

<?php

   echo Phalcon\Text::humanize('start-a-horse'); // 'start a horse'
   echo Phalcon\Text::humanize('five_cats'); // 'five cats'
Abstract class Phalcon\Translate

Source on GitHub

Abstract class Phalcon\Translate\Adapter

Source on GitHub

Base class for Phalcon\Translate adapters

Methods

public __construct (array $options)

...

public setInterpolator (Phalcon\Translate\InterpolatorInterface $interpolator)

...

public string t (string $translateKey, [array $placeholders])

Returns the translation string of the given key

public string _ (string $translateKey, [array $placeholders])

Returns the translation string of the given key (alias of method ‘t’)

public offsetSet (string $offset, string $value)

Sets a translation value

public offsetExists (mixed $translateKey)

Check whether a translation key exists

public offsetUnset (string $offset)

Unsets a translation from the dictionary

public string offsetGet (string $translateKey)

Returns the translation related to the given key

protected replacePlaceholders (mixed $translation, [mixed $placeholders])

Replaces placeholders by the values passed

Class Phalcon\Translate\Adapter\Csv

extends abstract class Phalcon\Translate\Adapter

implements Phalcon\Translate\AdapterInterface, ArrayAccess

Source on GitHub

Allows to define translation lists using CSV file

Methods

public __construct (array $options)

Phalcon\Translate\Adapter\Csv constructor

private _load (string $file, int $length, string $delimiter, string $enclosure)

Load translates from file

public query (mixed $index, [mixed $placeholders])

Returns the translation related to the given key

public exists (mixed $index)

Check whether is defined a translation key in the internal array

public setInterpolator (Phalcon\Translate\InterpolatorInterface $interpolator) inherited from Phalcon\Translate\Adapter

...

public string t (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key

public string _ (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key (alias of method ‘t’)

public offsetSet (string $offset, string $value) inherited from Phalcon\Translate\Adapter

Sets a translation value

public offsetExists (mixed $translateKey) inherited from Phalcon\Translate\Adapter

Check whether a translation key exists

public offsetUnset (string $offset) inherited from Phalcon\Translate\Adapter

Unsets a translation from the dictionary

public string offsetGet (string $translateKey) inherited from Phalcon\Translate\Adapter

Returns the translation related to the given key

protected replacePlaceholders (mixed $translation, [mixed $placeholders]) inherited from Phalcon\Translate\Adapter

Replaces placeholders by the values passed

Class Phalcon\Translate\Adapter\Gettext

extends abstract class Phalcon\Translate\Adapter

implements Phalcon\Translate\AdapterInterface, ArrayAccess

Source on GitHub

Allows translate using gettext

Methods

public getDirectory ()

public getDefaultDomain ()

public getLocale ()

public getCategory ()

public __construct (array $options)

Phalcon\Translate\Adapter\Gettext constructor

public string query (string $index, [array $placeholders])

Returns the translation related to the given key

public exists (mixed $index)

Check whether is defined a translation key in the internal array

public nquery (mixed $msgid1, mixed $msgid2, mixed $count, [mixed $placeholders], [mixed $domain])

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

public setDomain (mixed $domain)

Changes the current domain (i.e. the translation file)

public resetDomain ()

Sets the default domain

public setDefaultDomain (mixed $domain)

Sets the domain default to search within when calls are made to gettext()

public setDirectory (mixed $directory)

Sets the path for a domain

<?php

 // Set the directory path
 $gettext->setDirectory('/path/to/the/messages');

 // Set the domains and directories path
 $gettext->setDirectory([
    'messages' => '/path/to/the/messages',
    'another'  => '/path/to/the/another'
 ]);

public setLocale (mixed $category, mixed $locale)

Sets locale information

<?php

 // Set locale to Dutch
 $gettext->setLocale(LC_ALL, 'nl_NL');

 // Try different possible locale names for german
 $gettext->setLocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');

protected prepareOptions (array $options)

Validator for constructor

protected getOptionsDefault ()

Gets default options

public setInterpolator (Phalcon\Translate\InterpolatorInterface $interpolator) inherited from Phalcon\Translate\Adapter

...

public string t (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key

public string _ (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key (alias of method ‘t’)

public offsetSet (string $offset, string $value) inherited from Phalcon\Translate\Adapter

Sets a translation value

public offsetExists (mixed $translateKey) inherited from Phalcon\Translate\Adapter

Check whether a translation key exists

public offsetUnset (string $offset) inherited from Phalcon\Translate\Adapter

Unsets a translation from the dictionary

public string offsetGet (string $translateKey) inherited from Phalcon\Translate\Adapter

Returns the translation related to the given key

protected replacePlaceholders (mixed $translation, [mixed $placeholders]) inherited from Phalcon\Translate\Adapter

Replaces placeholders by the values passed

Class Phalcon\Translate\Adapter\NativeArray

extends abstract class Phalcon\Translate\Adapter

implements Phalcon\Translate\AdapterInterface, ArrayAccess

Source on GitHub

Allows to define translation lists using PHP arrays

Methods

public __construct (array $options)

Phalcon\Translate\Adapter\NativeArray constructor

public query (mixed $index, [mixed $placeholders])

Returns the translation related to the given key

public exists (mixed $index)

Check whether is defined a translation key in the internal array

public setInterpolator (Phalcon\Translate\InterpolatorInterface $interpolator) inherited from Phalcon\Translate\Adapter

...

public string t (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key

public string _ (string $translateKey, [array $placeholders]) inherited from Phalcon\Translate\Adapter

Returns the translation string of the given key (alias of method ‘t’)

public offsetSet (string $offset, string $value) inherited from Phalcon\Translate\Adapter

Sets a translation value

public offsetExists (mixed $translateKey) inherited from Phalcon\Translate\Adapter

Check whether a translation key exists

public offsetUnset (string $offset) inherited from Phalcon\Translate\Adapter

Unsets a translation from the dictionary

public string offsetGet (string $translateKey) inherited from Phalcon\Translate\Adapter

Returns the translation related to the given key

protected replacePlaceholders (mixed $translation, [mixed $placeholders]) inherited from Phalcon\Translate\Adapter

Replaces placeholders by the values passed

Class Phalcon\Translate\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Translate\Interpolator\AssociativeArray

implements Phalcon\Translate\InterpolatorInterface

Source on GitHub

Methods

public replacePlaceholders (mixed $translation, [mixed $placeholders])

Replaces placeholders by the values passed

Class Phalcon\Translate\Interpolator\IndexedArray

implements Phalcon\Translate\InterpolatorInterface

Source on GitHub

Methods

public replacePlaceholders (mixed $translation, [mixed $placeholders])

Replaces placeholders by the values passed

Class Phalcon\Validation

extends abstract class Phalcon\Di\Injectable

implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\ValidationInterface

Source on GitHub

Allows to validate data using custom or built-in validators

Methods

public setValidators (mixed $validators)

...

public __construct ([array $validators])

Phalcon\Validation constructor

public Phalcon\Validation\Message\Group validate ([array | object $data], [object $entity])

Validate a set of data according to a set of rules

public add (mixed $field, Phalcon\Validation\ValidatorInterface $validator)

Adds a validator to a field

public rule (mixed $field, Phalcon\Validation\ValidatorInterface $validator)

Alias of add method

public rules (mixed $field, array $validators)

Adds the validators to a field

public Phalcon\Validation setFilters (string $field, array | string $filters)

Adds filters to the field

public mixed getFilters ([string $field])

Returns all the filters or a specific one

public getValidators ()

Returns the validators added to the validation

public setEntity (object $entity)

Sets the bound entity

public object getEntity ()

Returns the bound entity

public setDefaultMessages ([array $messages])

Adds default messages to validators

public getDefaultMessage (mixed $type)

Get default message for validator type

public getMessages ()

Returns the registered validators

public setLabels (array $labels)

Adds labels for fields

public string getLabel (string $field)

Get label for field

public appendMessage (Phalcon\Validation\MessageInterface $message)

Appends a message to the messages list

public Phalcon\Validation bind (object $entity, array | object $data)

Assigns the data to an entity The entity is used to obtain the validation values

public mixed getValue (string $field)

Gets the a value to validate in the array/object data source

protected preChecking (mixed $field, Phalcon\Validation\ValidatorInterface $validator)

Internal validations, if it returns true, then skip the current validator

public setDI (Phalcon\DiInterface $dependencyInjector) inherited from Phalcon\Di\Injectable

Sets the dependency injector

public getDI () inherited from Phalcon\Di\Injectable

Returns the internal dependency injector

public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager) inherited from Phalcon\Di\Injectable

Sets the event manager

public getEventsManager () inherited from Phalcon\Di\Injectable

Returns the internal event manager

public __get (mixed $propertyName) inherited from Phalcon\Di\Injectable

Magic method __get

Abstract class Phalcon\Validation\CombinedFieldsValidator

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Methods

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

abstract public validate (Phalcon\Validation $validation, mixed $attribute) inherited from Phalcon\Validation\Validator

Executes the validation

Class Phalcon\Validation\Exception

extends class Phalcon\Exception

implements Throwable

Source on GitHub

Methods

final private Exception __clone () inherited from Exception

Clone the exception

public __construct ([string $message], [int $code], [Exception $previous]) inherited from Exception

Exception constructor

public __wakeup () inherited from Exception

...

final public string getMessage () inherited from Exception

Gets the Exception message

final public int getCode () inherited from Exception

Gets the Exception code

final public string getFile () inherited from Exception

Gets the file in which the exception occurred

final public int getLine () inherited from Exception

Gets the line in which the exception occurred

final public array getTrace () inherited from Exception

Gets the stack trace

final public Exception getPrevious () inherited from Exception

Returns previous Exception

final public Exception getTraceAsString () inherited from Exception

Gets the stack trace as a string

public string __toString () inherited from Exception

String representation of the exception

Class Phalcon\Validation\Message

implements Phalcon\Validation\MessageInterface

Source on GitHub

Encapsulates validation info generated in the validation process

Methods

public __construct (mixed $message, [mixed $field], [mixed $type], [mixed $code])

Phalcon\Validation\Message constructor

public setType (mixed $type)

Sets message type

public getType ()

Returns message type

public setMessage (mixed $message)

Sets verbose message

public getMessage ()

Returns verbose message

public setField (mixed $field)

Sets field name related to message

public mixed getField ()

Returns field name related to message

public setCode (mixed $code)

Sets code for the message

public getCode ()

Returns the message code

public __toString ()

Magic __toString method returns verbose message

public static __set_state (array $message)

Magic __set_state helps to recover messsages from serialization

Class Phalcon\Validation\Message\Group

implements Countable, ArrayAccess, Iterator, Traversable

Source on GitHub

Represents a group of validation messages

Methods

public __construct ([array $messages])

Phalcon\Validation\Message\Group constructor

public Phalcon\Validation\Message offsetGet (int $index)

Gets an attribute a message using the array syntax

<?php

 print_r($messages[0]);

public offsetSet (int $index, Phalcon\Validation\Message $message)

Sets an attribute using the array-syntax

<?php

 $messages[0] = new \Phalcon\Validation\Message('This is a message');

public boolean offsetExists (int $index)

Checks if an index exists

<?php

 var_dump(isset($message['database']));

public offsetUnset (string $index)

Removes a message from the list

<?php

 unset($message['database']);

public appendMessage (Phalcon\Validation\MessageInterface $message)

Appends a message to the group

<?php

 $messages->appendMessage(new \Phalcon\Validation\Message('This is a message'));

public appendMessages (Phalcon\Validation\MessageInterface[] $messages)

Appends an array of messages to the group

<?php

 $messages->appendMessages($messagesArray);

public array filter (string $fieldName)

Filters the message group by field name

public count ()

Returns the number of messages in the list

public rewind ()

Rewinds the internal iterator

public current ()

Returns the current message in the iterator

public key ()

Returns the current position/key in the iterator

public next ()

Moves the internal iteration pointer to the next position

public valid ()

Check if the current message in the iterator is valid

public static Phalcon\Validation\Message\Group __set_state (array $group)

Magic __set_state helps to re-build messages variable when exporting

Abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

This is a base class for validators

Methods

public __construct ([array $options])

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key)

Checks if an option has been defined

public hasOption (mixed $key)

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue])

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value)

Sets an option in the validator

abstract public validate (Phalcon\Validation $validation, mixed $attribute)

Executes the validation

Class Phalcon\Validation\Validator\Alnum

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check for alphanumeric character(s)

<?php

 use Phalcon\Validation\Validator\Alnum as AlnumValidator;

 $validator->add('username', new AlnumValidator([
     'message' => ':field must contain only alphanumeric characters'
 ]));

 $validator->add(['username', 'name'], new AlnumValidator([
     'message' => [
         'username' => 'username must contain only alphanumeric characters',
         'name' => 'name must contain only alphanumeric characters'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Alpha

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check for alphabetic character(s)

<?php

 use Phalcon\Validation\Validator\Alpha as AlphaValidator;

 $validator->add('username', new AlphaValidator([
     'message' => ':field must contain only letters'
 ]));

 $validator->add(['username', 'name'], new AlphaValidator([
     'message' => [
         'username' => 'username must contain only letters',
         'name' => 'name must contain only letters'
    ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Between

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Validates that a value is between an inclusive range of two values. For a value x, the test is passed if minimum<=x<=maximum.

<?php

 use Phalcon\Validation\Validator\Between;

 $validator->add('price', new Between([
     'minimum' => 0,
     'maximum' => 100,
     'message' => 'The price must be between 0 and 100'
 ]));

 $validator->add(['price', 'amount'], new Between([
     'minimum' => [
         'price' => 0,
         'amount' => 0
     ],
     'maximum' => [
         'price' => 100,
         'amount' => 50
     ],
     'message' => [
         'price' => 'The price must be between 0 and 100',
         'amount' => 'The amount must be between 0 and 50'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Confirmation

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks that two values have the same value

<?php

 use Phalcon\Validation\Validator\Confirmation;

 $validator->add('password', new Confirmation([
     'message' => 'Password doesn\'t match confirmation',
     'with' => 'confirmPassword'
 ]));

 $validator->add(['password', 'email'], new Confirmation([
     'message' => [
         'password' => 'Password doesn\'t match confirmation',
         'email' => 'Email  doesn\'t match confirmation'
     ],
     'with' => [
         'password => 'confirmPassword',
         'email' => 'confirmEmail'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

final protected compare (mixed $a, mixed $b)

Compare strings

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\CreditCard

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value has a valid credit card number

<?php

 use Phalcon\Validation\Validator\CreditCard as CreditCardValidator;

 $validator->add('creditcard', new CreditCardValidator([
     'message' => 'The credit card number is not valid'
 ]));

 $validator->add(['creditcard', 'secondCreditCard'], new CreditCardValidator([
     'message' => [
         'creditcard' => 'The credit card number is not valid',
         'secondCreditCard' => 'The second credit card number is not valid'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

private boolean verifyByLuhnAlgorithm (string $number)

is a simple checksum formula used to validate a variety of identification numbers

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Date

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value is a valid date

<?php

 use Phalcon\Validation\Validator\Date as DateValidator;

 $validator->add('date', new DateValidator([
     'format' => 'd-m-Y',
     'message' => 'The date is invalid'
 ]));

 $validator->add(['date','anotherDate'], new DateValidator([
     'format' => [
         'date' => 'd-m-Y',
         'anotherDate' => 'Y-m-d'
     ],
     'message' => [
         'date' => 'The date is invalid',
         'anotherDate' => 'The another date is invalid'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

private checkDate (mixed $value, mixed $format)

...

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Digit

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check for numeric character(s)

<?php

 use Phalcon\Validation\Validator\Digit as DigitValidator;

 $validator->add('height', new DigitValidator([
     'message' => ':field must be numeric'
 ]));

 $validator->add(['height', 'width'], new DigitValidator([
     'message' => [
         'height' => 'height must be numeric',
         'width' => 'width must be numeric'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Email

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value has a correct e-mail format

<?php

 use Phalcon\Validation\Validator\Email as EmailValidator;

 $validator->add('email', new EmailValidator([
     'message' => 'The e-mail is not valid'
 ]));

 $validator->add(['email', 'anotherEmail'], new EmailValidator([
     'message' => [
         'email' => 'The e-mail is not valid',
         'anotherEmail' => 'The another e-mail is not valid'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\ExclusionIn

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check if a value is not included into a list of values

<?php

 use Phalcon\Validation\Validator\ExclusionIn;

 $validator->add('status', new ExclusionIn([
     'message' => 'The status must not be A or B',
     'domain' => ['A', 'B']
 ]));

 $validator->add(['status', 'type'], new ExclusionIn([
     'message' => [
         'status' => 'The status must not be A or B',
         'type' => 'The type must not be 1 or 2'
     ],
     'domain' => [
         'status' => ['A', 'B'],
         'type' => [1, 2]
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\File

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value has a correct file

<?php

 use Phalcon\Validation\Validator\File as FileValidator;

 $validator->add('file', new FileValidator([
     'maxSize' => '2M',
     'messageSize' => ':field exceeds the max filesize (:max)',
     'allowedTypes' => array('image/jpeg', 'image/png'),
     'messageType' => 'Allowed file types are :types',
     'maxResolution' => '800x600',
     'messageMaxResolution' => 'Max resolution of :field is :max'
 ]));

 $validator->add(['file', 'anotherFile'], new FileValidator([
     'maxSize' => [
         'file' => '2M',
         'anotherFile' => '4M'
     ],
     'messageSize' => [
         'file' => 'file exceeds the max filesize 2M',
         'anotherFile' => 'anotherFile exceeds the max filesize 4M',
     'allowedTypes' => [
         'file' => ['image/jpeg', 'image/png'],
         'anotherFile' => ['image/gif', 'image/bmp']
     ],
     'messageType' => [
         'file' => 'Allowed file types are image/jpeg and image/png',
         'anotherFile' => 'Allowed file types are image/gif and image/bmp'
     ],
     'maxResolution' => [
         'file' => '800x600',
         'anotherFile' => '1024x768'
     ],
     'messageMaxResolution' => [
         'file' => 'Max resolution of file is 800x600',
         'anotherFile' => 'Max resolution of file is 1024x768'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public isAllowEmpty (Phalcon\Validation $validation, mixed $field)

Check on empty

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Identical

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value is identical to other

<?php

 use Phalcon\Validation\Validator\Identical;

 $validator->add('terms', new Identical([
     'accepted' => 'yes',
     'message' => 'Terms and conditions must be accepted'
 ]));

 $validator->add(['terms', 'anotherTerms'], new Identical([
     'accepted' => [
         'terms' => 'yes',
         'anotherTerms' => 'yes'
     ],
     'message' => [
         'terms' => 'Terms and conditions must be accepted',
         'anotherTerms' => 'Another terms  must be accepted'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\InclusionIn

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check if a value is included into a list of values

<?php

 use Phalcon\Validation\Validator\InclusionIn;

 $validator->add('status', new InclusionIn([
     'message' => 'The status must be A or B',
     'domain' => array('A', 'B')
 ]));

 $validator->add(['status', 'type'], new InclusionIn([
     'message' => [
         'status' => 'The status must be A or B',
         'type' => 'The status must be 1 or 2'
     ],
     'domain' => [
         'status' => ['A', 'B'],
         'type' => [1, 2]
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Numericality

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check for a valid numeric value

<?php

 use Phalcon\Validation\Validator\Numericality;

 $validator->add('price', new Numericality([
     'message' => ':field is not numeric'
 ]));

 $validator->add(['price', 'amount'], new Numericality([
     'message' => [
         'price' => 'price is not numeric',
         'amount' => 'amount is not numeric'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\PresenceOf

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Validates that a value is not null or empty string

<?php

 use Phalcon\Validation\Validator\PresenceOf;

 $validator->add('name', new PresenceOf([
     'message' => 'The name is required'
 ]));

 $validator->add(['name', 'email'], new PresenceOf([
     'message' => [
         'name' => 'The name is required',
         'email' => 'The email is required'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Regex

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Allows validate if the value of a field matches a regular expression

<?php

 use Phalcon\Validation\Validator\Regex as RegexValidator;

 $validator->add('created_at', new RegexValidator([
     'pattern' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/',
     'message' => 'The creation date is invalid'
 ]));

 $validator->add(['created_at', 'name'], new RegexValidator([
     'pattern' => [
         'created_at' => '/^[0-9]{4}[-\/](0[1-9]|1[12])[-\/](0[1-9]|[12][0-9]|3[01])$/',
         'name' => '/^[a-z]$/'
     ],
     'message' => [
         'created_at' => 'The creation date is invalid',
         'name' => ' 'The name is invalid'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\StringLength

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Validates that a string has the specified maximum and minimum constraints The test is passed if for a string’s length L, min<=L<=max, i.e. L must be at least min, and at most max.

<?php

 use Phalcon\Validation\Validator\StringLength as StringLength;

 $validation->add('name_last', new StringLength([
     'max' => 50,
     'min' => 2,
     'messageMaximum' => 'We don\'t like really long names',
     'messageMinimum' => 'We want more than just their initials'
 ]));

 $validation->add(['name_last', 'name_first'], new StringLength([
     'max' => [
         'name_last' => 50,
         'name_first' => 40
     ],
     'min' => [
         'name_last' => 2,
         'name_first' => 4
     ],
     'messageMaximum' => [
         'name_last' => 'We don\'t like really long last names',
         'name_first' => 'We don\'t like really long first names'
     ],
     'messageMinimum' => [
         'name_last' => 'We don\'t like too short last names',
         'name_first' => 'We don\'t like too short first names',
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Uniqueness

extends abstract class Phalcon\Validation\CombinedFieldsValidator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Check that a field is unique in the related table

  <?php

   use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator;

   $validator->add('username', new UniquenessValidator([
       'model' => new Users(),
       'message' => ':field must be unique'
   ]));

Different attribute from the field:
  <?php

   $validator->add('username', new UniquenessValidator([
       'model' => new Users(),
       'attribute' => 'nick'
   ]));

In model:
  <?php

   $validator->add('username', new UniquenessValidator());

Combination of fields in model:
  <?php

   $validator->add(['firstName', 'lastName'], new UniquenessValidator());

It is possible to convert values before validation. This is useful in situations where values need to be converted to do the database lookup:
<?php

 $validator->add('username', new UniquenessValidator([
     'convert' => function (array $values) {
         $values['username'] = strtolower($values['username']);

         return $values;
     }
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

protected isUniqueness (Phalcon\Validation $validation, mixed $field)

...

protected getColumnNameReal (mixed $record, mixed $field)

The column map is used in the case to get real column name

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Validation\Validator\Url

extends abstract class Phalcon\Validation\Validator

implements Phalcon\Validation\ValidatorInterface

Source on GitHub

Checks if a value has a url format

<?php

 use Phalcon\Validation\Validator\Url as UrlValidator;

 $validator->add('url', new UrlValidator([
     'message' => ':field must be a url'
 ]));

 $validator->add(['url', 'homepage'], new UrlValidator([
     'message' => [
         'url' => 'url must be a url',
         'homepage' => 'homepage must be a url'
     ]
 ]));
Methods

public validate (Phalcon\Validation $validation, mixed $field)

Executes the validation

public __construct ([array $options]) inherited from Phalcon\Validation\Validator

Phalcon\Validation\Validator constructor

public isSetOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option has been defined

public hasOption (mixed $key) inherited from Phalcon\Validation\Validator

Checks if an option is defined

public getOption (mixed $key, [mixed $defaultValue]) inherited from Phalcon\Validation\Validator

Returns an option in the validator’s options Returns null if the option hasn’t set

public setOption (mixed $key, mixed $value) inherited from Phalcon\Validation\Validator

Sets an option in the validator

Class Phalcon\Version

Source on GitHub

This class allows to get the installed version of the framework

Constants

integer VERSION_MAJOR

integer VERSION_MEDIUM

integer VERSION_MINOR

integer VERSION_SPECIAL

integer VERSION_SPECIAL_NUMBER

Methods

protected static _getVersion ()

Area where the version number is set. The format is as follows: ABBCCDE A - Major version B - Med version (two digits) C - Min version (two digits) D - Special release: 1 = Alpha, 2 = Beta, 3 = RC, 4 = Stable E - Special release version i.e. RC1, Beta2 etc.

final protected static _getSpecial (mixed $special)

Translates a number to a special release If Special release = 1 this function will return ALPHA

public static get ()

Returns the active version (string)

<?php

 echo Phalcon\Version::get();

public static getId ()

Returns the numeric active version

<?php

 echo Phalcon\Version::getId();

public static getPart (mixed $part)

Returns a specific part of the version. If the wrong parameter is passed it will return the full version

<?php

 echo Phalcon\Version::getPart(Phalcon\Version::VERSION_MAJOR);
Interface Phalcon\Acl\AdapterInterface

Source on GitHub

Methods

abstract public setDefaultAction (mixed $defaultAccess)

...

abstract public getDefaultAction ()

...

abstract public setNoArgumentsDefaultAction (mixed $defaultAccess)

...

abstract public getNoArgumentsDefaultAction ()

...

abstract public addRole (mixed $role, [mixed $accessInherits])

...

abstract public addInherit (mixed $roleName, mixed $roleToInherit)

...

abstract public isRole (mixed $roleName)

...

abstract public isResource (mixed $resourceName)

...

abstract public addResource (mixed $resourceObject, mixed $accessList)

...

abstract public addResourceAccess (mixed $resourceName, mixed $accessList)

...

abstract public dropResourceAccess (mixed $resourceName, mixed $accessList)

...

abstract public allow (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func])

...

abstract public deny (mixed $roleName, mixed $resourceName, mixed $access, [mixed $func])

...

abstract public isAllowed (mixed $roleName, mixed $resourceName, mixed $access, [array $parameters])

...

abstract public getActiveRole ()

...

abstract public getActiveResource ()

...

abstract public getActiveAccess ()

...

abstract public getRoles ()

...

abstract public getResources ()

...

Interface Phalcon\Acl\ResourceAware

Source on GitHub

Methods

abstract public getResourceName ()

...

Interface Phalcon\Acl\ResourceInterface

Source on GitHub

Methods

abstract public getName ()

...

abstract public getDescription ()

...

abstract public __toString ()

...

Interface Phalcon\Acl\RoleAware

Source on GitHub

Methods

abstract public getRoleName ()

...

Interface Phalcon\Acl\RoleInterface

Source on GitHub

Methods

abstract public getName ()

...

abstract public getDescription ()

...

abstract public __toString ()

...

Interface Phalcon\Annotations\AdapterInterface

Source on GitHub

Methods

abstract public setReader (Phalcon\Annotations\ReaderInterface $reader)

...

abstract public getReader ()

...

abstract public get (mixed $className)

...

abstract public getMethods (mixed $className)

...

abstract public getMethod (mixed $className, mixed $methodName)

...

abstract public getProperties (mixed $className)

...

abstract public getProperty (mixed $className, mixed $propertyName)

...

Interface Phalcon\Annotations\ReaderInterface

Source on GitHub

Methods

abstract public parse (mixed $className)

...

abstract public static parseDocBlock (mixed $docBlock, [mixed $file], [mixed $line])

...

Interface Phalcon\Assets\FilterInterface

Source on GitHub

Methods

abstract public filter (mixed $content)

...

Interface Phalcon\Cache\BackendInterface

Source on GitHub

Methods

abstract public start (mixed $keyName, [mixed $lifetime])

...

abstract public stop ([mixed $stopBuffer])

...

abstract public getFrontend ()

...

abstract public getOptions ()

...

abstract public isFresh ()

...

abstract public isStarted ()

...

abstract public setLastKey (mixed $lastKey)

...

abstract public getLastKey ()

...

abstract public get (mixed $keyName, [mixed $lifetime])

...

abstract public save ([mixed $keyName], [mixed $content], [mixed $lifetime], [mixed $stopBuffer])

...

abstract public delete (mixed $keyName)

...

abstract public queryKeys ([mixed $prefix])

...

abstract public exists ([mixed $keyName], [mixed $lifetime])

...

Interface Phalcon\Cache\FrontendInterface

Source on GitHub

Methods

abstract public getLifetime ()

...

abstract public isBuffering ()

...

abstract public start ()

...

abstract public getContent ()

...

abstract public stop ()

...

abstract public beforeStore (mixed $data)

...

abstract public afterRetrieve (mixed $data)

...

Interface Phalcon\Cli\DispatcherInterface

implements Phalcon\DispatcherInterface

Source on GitHub

Methods

abstract public setTaskSuffix (mixed $taskSuffix)

...

abstract public setDefaultTask (mixed $taskName)

...

abstract public setTaskName (mixed $taskName)

...

abstract public getTaskName ()

...

abstract public getLastTask ()

...

abstract public getActiveTask ()

...

abstract public setActionSuffix (mixed $actionSuffix) inherited from Phalcon\DispatcherInterface

...

abstract public getActionSuffix () inherited from Phalcon\DispatcherInterface

...

abstract public setDefaultNamespace (mixed $defaultNamespace) inherited from Phalcon\DispatcherInterface

...

abstract public setDefaultAction (mixed $actionName) inherited from Phalcon\DispatcherInterface

...

abstract public setNamespaceName (mixed $namespaceName) inherited from Phalcon\DispatcherInterface

...

abstract public setModuleName (mixed $moduleName) inherited from Phalcon\DispatcherInterface

...

abstract public setActionName (mixed $actionName) inherited from Phalcon\DispatcherInterface

...

abstract public getActionName () inherited from Phalcon\DispatcherInterface

...

abstract public setParams (mixed $params) inherited from Phalcon\DispatcherInterface

...

abstract public getParams () inherited from Phalcon\DispatcherInterface

...

abstract public setParam (mixed $param, mixed $value) inherited from Phalcon\DispatcherInterface

...

abstract public getParam (mixed $param, [mixed $filters]) inherited from Phalcon\DispatcherInterface

...

abstract public hasParam (mixed $param) inherited from Phalcon\DispatcherInterface

...

abstract public isFinished () inherited from Phalcon\DispatcherInterface

...

abstract public getReturnedValue () inherited from Phalcon\DispatcherInterface

...

abstract public dispatch () inherited from Phalcon\DispatcherInterface

...

abstract public forward (mixed $forward) inherited from Phalcon\DispatcherInterface

...

Interface Phalcon\Cli\RouterInterface

Source on GitHub

Methods

abstract public setDefaultModule (mixed $moduleName)

...

abstract public setDefaultTask (mixed $taskName)

...

abstract public setDefaultAction (mixed $actionName)

...

abstract public setDefaults (array $defaults)

...

abstract public handle ([mixed $arguments])

...

abstract public add (mixed $pattern, [mixed $paths])

...

abstract public getModuleName ()

...

abstract public getTaskName ()

...

abstract public getActionName ()

...

abstract public getParams ()

...

abstract public getMatchedRoute ()

...

abstract public getMatches ()

...

abstract public wasMatched ()

...

abstract public getRoutes ()

...

abstract public getRouteById (mixed $id)

...

abstract public getRouteByName (mixed $name)

...

Interface Phalcon\Cli\Router\RouteInterface

Source on GitHub

Methods

abstract public compilePattern (mixed $pattern)

...

abstract public reConfigure (mixed $pattern, [mixed $paths])

...

abstract public getName ()

...

abstract public setName (mixed $name)

...

abstract public getRouteId ()

...

abstract public getPattern ()

...

abstract public getCompiledPattern ()

...

abstract public getPaths ()

...

abstract public getReversedPaths ()

...

abstract public static reset ()

...

Interface Phalcon\Cli\TaskInterface

Source on GitHub

Interface Phalcon\CryptInterface

Source on GitHub

Methods

abstract public setCipher (mixed $cipher)

...

abstract public getCipher ()

...

abstract public setKey (mixed $key)

...

abstract public getKey ()

...

abstract public encrypt (mixed $text, [mixed $key])

...

abstract public decrypt (mixed $text, [mixed $key])

...

abstract public encryptBase64 (mixed $text, [mixed $key])

...

abstract public decryptBase64 (mixed $text, [mixed $key])

...

abstract public getAvailableCiphers ()

...

Interface Phalcon\Db\AdapterInterface

Source on GitHub

Methods

abstract public fetchOne (mixed $sqlQuery, [mixed $fetchMode], [mixed $placeholders])

...

abstract public fetchAll (mixed $sqlQuery, [mixed $fetchMode], [mixed $placeholders])

...

abstract public insert (mixed $table, array $values, [mixed $fields], [mixed $dataTypes])

...

abstract public update (mixed $table, mixed $fields, mixed $values, [mixed $whereCondition], [mixed $dataTypes])

...

abstract public delete (mixed $table, [mixed $whereCondition], [mixed $placeholders], [mixed $dataTypes])

...

abstract public getColumnList (mixed $columnList)

...

abstract public limit (mixed $sqlQuery, mixed $number)

...

abstract public tableExists (mixed $tableName, [mixed $schemaName])

...

abstract public viewExists (mixed $viewName, [mixed $schemaName])

...

abstract public forUpdate (mixed $sqlQuery)

...

abstract public sharedLock (mixed $sqlQuery)

...

abstract public createTable (mixed $tableName, mixed $schemaName, array $definition)

...

abstract public dropTable (mixed $tableName, [mixed $schemaName], [mixed $ifExists])

...

abstract public createView (mixed $viewName, array $definition, [mixed $schemaName])

...

abstract public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

...

abstract public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

...

abstract public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

...

abstract public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

...

abstract public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

...

abstract public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

...

abstract public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

...

abstract public dropPrimaryKey (mixed $tableName, mixed $schemaName)

...

abstract public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

...

abstract public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

...

abstract public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

...

abstract public listTables ([mixed $schemaName])

...

abstract public listViews ([mixed $schemaName])

...

abstract public getDescriptor ()

...

abstract public getConnectionId ()

...

abstract public getSQLStatement ()

...

abstract public getRealSQLStatement ()

...

abstract public getSQLVariables ()

...

abstract public getSQLBindTypes ()

...

abstract public getType ()

...

abstract public getDialectType ()

...

abstract public getDialect ()

...

abstract public connect ([array $descriptor])

...

abstract public query (mixed $sqlStatement, [mixed $placeholders], [mixed $dataTypes])

...

abstract public execute (mixed $sqlStatement, [mixed $placeholders], [mixed $dataTypes])

...

abstract public affectedRows ()

...

abstract public close ()

...

abstract public escapeIdentifier (mixed $identifier)

...

abstract public escapeString (mixed $str)

...

abstract public lastInsertId ([mixed $sequenceName])

...

abstract public begin ([mixed $nesting])

...

abstract public rollback ([mixed $nesting])

...

abstract public commit ([mixed $nesting])

...

abstract public isUnderTransaction ()

...

abstract public getInternalHandler ()

...

abstract public describeIndexes (mixed $table, [mixed $schema])

...

abstract public describeReferences (mixed $table, [mixed $schema])

...

abstract public tableOptions (mixed $tableName, [mixed $schemaName])

...

abstract public useExplicitIdValue ()

...

abstract public getDefaultIdValue ()

...

abstract public supportSequences ()

...

abstract public createSavepoint (mixed $name)

...

abstract public releaseSavepoint (mixed $name)

...

abstract public rollbackSavepoint (mixed $name)

...

abstract public setNestedTransactionsWithSavepoints (mixed $nestedTransactionsWithSavepoints)

...

abstract public isNestedTransactionsWithSavepoints ()

...

abstract public getNestedTransactionSavepointName ()

...

abstract public describeColumns (mixed $table, [mixed $schema])

...

Interface Phalcon\Db\ColumnInterface

Source on GitHub

Methods

abstract public getSchemaName ()

...

abstract public getName ()

...

abstract public getType ()

...

abstract public getTypeReference ()

...

abstract public getTypeValues ()

...

abstract public getSize ()

...

abstract public getScale ()

...

abstract public isUnsigned ()

...

abstract public isNotNull ()

...

abstract public isPrimary ()

...

abstract public isAutoIncrement ()

...

abstract public isNumeric ()

...

abstract public isFirst ()

...

abstract public getAfterPosition ()

...

abstract public getBindType ()

...

abstract public getDefault ()

...

abstract public hasDefault ()

...

abstract public static __set_state (array $data)

...

Interface Phalcon\Db\DialectInterface

Source on GitHub

Methods

abstract public limit (mixed $sqlQuery, mixed $number)

...

abstract public forUpdate (mixed $sqlQuery)

...

abstract public sharedLock (mixed $sqlQuery)

...

abstract public select (array $definition)

...

abstract public getColumnList (array $columnList)

...

abstract public getColumnDefinition (Phalcon\Db\ColumnInterface $column)

...

abstract public addColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column)

...

abstract public modifyColumn (mixed $tableName, mixed $schemaName, Phalcon\Db\ColumnInterface $column, [Phalcon\Db\ColumnInterface $currentColumn])

...

abstract public dropColumn (mixed $tableName, mixed $schemaName, mixed $columnName)

...

abstract public addIndex (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

...

abstract public dropIndex (mixed $tableName, mixed $schemaName, mixed $indexName)

...

abstract public addPrimaryKey (mixed $tableName, mixed $schemaName, Phalcon\Db\IndexInterface $index)

...

abstract public dropPrimaryKey (mixed $tableName, mixed $schemaName)

...

abstract public addForeignKey (mixed $tableName, mixed $schemaName, Phalcon\Db\ReferenceInterface $reference)

...

abstract public dropForeignKey (mixed $tableName, mixed $schemaName, mixed $referenceName)

...

abstract public createTable (mixed $tableName, mixed $schemaName, array $definition)

...

abstract public createView (mixed $viewName, array $definition, [mixed $schemaName])

...

abstract public dropTable (mixed $tableName, mixed $schemaName)

...

abstract public dropView (mixed $viewName, [mixed $schemaName], [mixed $ifExists])

...

abstract public tableExists (mixed $tableName, [mixed $schemaName])

...

abstract public viewExists (mixed $viewName, [mixed $schemaName])

...

abstract public describeColumns (mixed $table, [mixed $schema])

...

abstract public listTables ([mixed $schemaName])

...

abstract public describeIndexes (mixed $table, [mixed $schema])

...

abstract public describeReferences (mixed $table, [mixed $schema])

...

abstract public tableOptions (mixed $table, [mixed $schema])

...

abstract public supportsSavepoints ()

...

abstract public supportsReleaseSavepoints ()

...

abstract public createSavepoint (mixed $name)

...

abstract public releaseSavepoint (mixed $name)

...

abstract public rollbackSavepoint (mixed $name)

...

Interface Phalcon\Db\IndexInterface

Source on GitHub

Methods

abstract public getName ()

...

abstract public getColumns ()

...

abstract public getType ()

...

abstract public static __set_state (array $data)

...

Interface Phalcon\Db\ReferenceInterface

Source on GitHub

Methods

abstract public getName ()

...

abstract public getSchemaName ()

...

abstract public getReferencedSchema ()

...

abstract public getColumns ()

...

abstract public getReferencedTable ()

...

abstract public getReferencedColumns ()

...

abstract public getOnDelete ()

...

abstract public getOnUpdate ()

...

abstract public static __set_state (array $data)

...

Interface Phalcon\Db\ResultInterface

Source on GitHub

Methods

abstract public execute ()

...

abstract public fetch ()

...

abstract public fetchArray ()

...

abstract public fetchAll ()

...

abstract public numRows ()

...

abstract public dataSeek (mixed $number)

...

abstract public setFetchMode (mixed $fetchMode)

...

abstract public getInternalResult ()

...

Interface Phalcon\DiInterface

implements ArrayAccess

Source on GitHub

Methods

abstract public set (mixed $name, mixed $definition, [mixed $shared])

...

abstract public setShared (mixed $name, mixed $definition)

...

abstract public remove (mixed $name)

...

abstract public attempt (mixed $name, mixed $definition, [mixed $shared])

...

abstract public get (mixed $name, [mixed $parameters])

...

abstract public getShared (mixed $name, [mixed $parameters])

...

abstract public setRaw (mixed $name, Phalcon\Di\ServiceInterface $rawDefinition)

...

abstract public getRaw (mixed $name)

...

abstract public getService (mixed $name)

...

abstract public has (mixed $name)

...

abstract public wasFreshInstance ()

...

abstract public getServices ()

...

abstract public static setDefault (Phalcon\DiInterface $dependencyInjector)

...

abstract public static getDefault ()

...

abstract public static reset ()

...

abstract public offsetExists (mixed $offset) inherited from ArrayAccess

...

abstract public offsetGet (mixed $offset) inherited from ArrayAccess

...

abstract public offsetSet (mixed $offset, mixed $value) inherited from ArrayAccess

...

abstract public offsetUnset (mixed $offset) inherited from ArrayAccess

...

Interface Phalcon\Di\InjectionAwareInterface

Source on GitHub

Methods

abstract public setDI (Phalcon\DiInterface $dependencyInjector)

...

abstract public getDI ()

...

Interface Phalcon\Di\ServiceInterface

Source on GitHub

Methods

abstract public getName ()

...

abstract public setShared (mixed $shared)

...

abstract public isShared ()

...

abstract public setDefinition (mixed $definition)

...

abstract public getDefinition ()

...

abstract public resolve ([mixed $parameters], [Phalcon\DiInterface $dependencyInjector])

...

abstract public setParameter (mixed $position, array $parameter)

...

abstract public static __set_state (array $attributes)

...

Interface Phalcon\DispatcherInterface

Source on GitHub

Methods

abstract public setActionSuffix (mixed $actionSuffix)

...

abstract public getActionSuffix ()

...

abstract public setDefaultNamespace (mixed $defaultNamespace)

...

abstract public setDefaultAction (mixed $actionName)

...

abstract public setNamespaceName (mixed $namespaceName)

...

abstract public setModuleName (mixed $moduleName)

...

abstract public setActionName (mixed $actionName)

...

abstract public getActionName ()

...

abstract public setParams (mixed $params)

...

abstract public getParams ()

...

abstract public setParam (mixed $param, mixed $value)

...

abstract public getParam (mixed $param, [mixed $filters])

...

abstract public hasParam (mixed $param)

...

abstract public isFinished ()

...

abstract public getReturnedValue ()

...

abstract public dispatch ()

...

abstract public forward (mixed $forward)

...

Interface Phalcon\EscaperInterface

Source on GitHub

Methods

abstract public setEncoding (mixed $encoding)

...

abstract public getEncoding ()

...

abstract public setHtmlQuoteType (mixed $quoteType)

...

abstract public escapeHtml (mixed $text)

...

abstract public escapeHtmlAttr (mixed $text)

...

abstract public escapeCss (mixed $css)

...

abstract public escapeJs (mixed $js)

...

abstract public escapeUrl (mixed $url)

...

Interface Phalcon\Events\EventInterface

Source on GitHub

Methods

abstract public getData ()

...

abstract public setData ([mixed $data])

...

abstract public getType ()

...

abstract public setType (mixed $type)

...

abstract public stop ()

...

abstract public isStopped ()

...

abstract public isCancelable ()

...

Interface Phalcon\Events\EventsAwareInterface

Source on GitHub

Methods

abstract public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)

...

abstract public getEventsManager ()

...

Interface Phalcon\Events\ManagerInterface

Source on GitHub

Methods

abstract public attach (mixed $eventType, mixed $handler)

...

abstract public detach (mixed $eventType, mixed $handler)

...

abstract public detachAll ([mixed $type])

...

abstract public fire (mixed $eventType, mixed $source, [mixed $data])

...

abstract public getListeners (mixed $type)

...

Interface Phalcon\FilterInterface

Source on GitHub

Methods

abstract public add (mixed $name, mixed $handler)

...

abstract public sanitize (mixed $value, mixed $filters)

...

abstract public getFilters ()

...

Interface Phalcon\Filter\UserFilterInterface

Source on GitHub

Methods

abstract public filter (mixed $value)

...

Interface Phalcon\FlashInterface

Source on GitHub

Methods

abstract public error (mixed $message)

...

abstract public notice (mixed $message)

...

abstract public success (mixed $message)

...

abstract public warning (mixed $message)

...

abstract public message (mixed $type, mixed $message)

...

Interface Phalcon\Forms\ElementInterface

Source on GitHub

Methods

abstract public setForm (Phalcon\Forms\Form $form)

...

abstract public getForm ()

...

abstract public setName (mixed $name)

...

abstract public getName ()

...

abstract public setFilters (mixed $filters)

...

abstract public addFilter (mixed $filter)

...

abstract public getFilters ()

...

abstract public addValidators (array $validators, [mixed $merge])

...

abstract public addValidator (Phalcon\Validation\ValidatorInterface $validator)

...

abstract public getValidators ()

...

abstract public prepareAttributes ([array $attributes], [mixed $useChecked])

...

abstract public setAttribute (mixed $attribute, mixed $value)

...

abstract public getAttribute (mixed $attribute, [mixed $defaultValue])

...

abstract public setAttributes (array $attributes)

...

abstract public getAttributes ()

...

abstract public setUserOption (mixed $option, mixed $value)

...

abstract public getUserOption (mixed $option, [mixed $defaultValue])

...

abstract public setUserOptions (array $options)

...

abstract public getUserOptions ()

...

abstract public setLabel (mixed $label)

...

abstract public getLabel ()

...

abstract public label ()

...

abstract public setDefault (mixed $value)

...

abstract public getDefault ()

...

abstract public getValue ()

...

abstract public getMessages ()

...

abstract public hasMessages ()

...

abstract public setMessages (Phalcon\Validation\Message\Group $group)

...

abstract public appendMessage (Phalcon\Validation\MessageInterface $message)

...

abstract public clear ()

...

abstract public render ([mixed $attributes])

...

Interface Phalcon\Http\CookieInterface

Source on GitHub

Methods

abstract public setValue (mixed $value)

...

abstract public getValue ([mixed $filters], [mixed $defaultValue])

...

abstract public send ()

...

abstract public delete ()

...

abstract public useEncryption (mixed $useEncryption)

...

abstract public isUsingEncryption ()

...

abstract public setExpiration (mixed $expire)

...

abstract public getExpiration ()

...

abstract public setPath (mixed $path)

...

abstract public getName ()

...

abstract public getPath ()

...

abstract public setDomain (mixed $domain)

...

abstract public getDomain ()

...

abstract public setSecure (mixed $secure)

...

abstract public getSecure ()

...

abstract public setHttpOnly (mixed $httpOnly)

...

abstract public getHttpOnly ()

...

Interface Phalcon\Http\RequestInterface

Source on GitHub

Methods

abstract public get ([mixed $name], [mixed $filters], [mixed $defaultValue])

...

abstract public getPost ([mixed $name], [mixed $filters], [mixed $defaultValue])

...

abstract public getQuery ([mixed $name], [mixed $filters], [mixed $defaultValue])

...

abstract public getServer (mixed $name)

...

abstract public has (mixed $name)

...

abstract public hasPost (mixed $name)

...

abstract public hasPut (mixed $name)

...

abstract public hasQuery (mixed $name)

...

abstract public hasServer (mixed $name)

...

abstract public getHeader (mixed $header)

...

abstract public getScheme ()

...

abstract public isAjax ()

...

abstract public isSoapRequested ()

...

abstract public isSecureRequest ()

...

abstract public getRawBody ()

...

abstract public getServerAddress ()

...

abstract public getServerName ()

...

abstract public getHttpHost ()

...

abstract public getPort ()

...

abstract public getClientAddress ([mixed $trustForwardedHeader])

...

abstract public getMethod ()

...

abstract public getUserAgent ()

...

abstract public isMethod (mixed $methods, [mixed $strict])

...

abstract public isPost ()

...

abstract public isGet ()

...

abstract public isPut ()

...

abstract public isHead ()

...

abstract public isDelete ()

...

abstract public isOptions ()

...

abstract public isPurge ()

...

abstract public isTrace ()

...

abstract public isConnect ()

...

abstract public hasFiles ([mixed $onlySuccessful])

...

abstract public getUploadedFiles ([mixed $onlySuccessful])

...

abstract public getHTTPReferer ()

...

abstract public getAcceptableContent ()

...

abstract public getBestAccept ()

...

abstract public getClientCharsets ()

...

abstract public getBestCharset ()

...

abstract public getLanguages ()

...

abstract public getBestLanguage ()

...

abstract public getBasicAuth ()

...

abstract public getDigestAuth ()

...

Interface Phalcon\Http\Request\FileInterface

Source on GitHub

Methods

abstract public getSize ()

...

abstract public getName ()

...

abstract public getTempName ()

...

abstract public getType ()

...

abstract public getRealType ()

...

abstract public moveTo (mixed $destination)

...

Interface Phalcon\Http\ResponseInterface

Source on GitHub

Methods

abstract public setStatusCode (mixed $code, [mixed $message])

...

abstract public getHeaders ()

...

abstract public setHeader (mixed $name, mixed $value)

...

abstract public setRawHeader (mixed $header)

...

abstract public resetHeaders ()

...

abstract public setExpires (DateTime $datetime)

...

abstract public setNotModified ()

...

abstract public setContentType (mixed $contentType, [mixed $charset])

...

abstract public setContentLength (mixed $contentLength)

...

abstract public redirect ([mixed $location], [mixed $externalRedirect], [mixed $statusCode])

...

abstract public setContent (mixed $content)

...

abstract public setJsonContent (mixed $content)

...

abstract public appendContent (mixed $content)

...

abstract public getContent ()

...

abstract public sendHeaders ()

...

abstract public sendCookies ()

...

abstract public send ()

...

abstract public setFileToSend (mixed $filePath, [mixed $attachmentName])

...

Interface Phalcon\Http\Response\CookiesInterface

Source on GitHub

Methods

abstract public useEncryption (mixed $useEncryption)

...

abstract public isUsingEncryption ()

...

abstract public set (mixed $name, [mixed $value], [mixed $expire], [mixed $path], [mixed $secure], [mixed $domain], [mixed $httpOnly])

...

abstract public get (mixed $name)

...

abstract public has (mixed $name)

...

abstract public delete (mixed $name)

...

abstract public send ()

...

abstract public reset ()

...

Interface Phalcon\Http\Response\HeadersInterface

Source on GitHub

Methods

abstract public set (mixed $name, mixed $value)

...

abstract public get (mixed $name)

...

abstract public setRaw (mixed $header)

...

abstract public send ()

...

abstract public reset ()

...

abstract public static __set_state (array $data)

...

Interface Phalcon\Image\AdapterInterface

Source on GitHub

Methods

abstract public resize ([mixed $width], [mixed $height], [mixed $master])

...

abstract public crop (mixed $width, mixed $height, [mixed $offsetX], [mixed $offsetY])

...

abstract public rotate (mixed $degrees)

...

abstract public flip (mixed $direction)

...

abstract public sharpen (mixed $amount)

...

abstract public reflection (mixed $height, [mixed $opacity], [mixed $fadeIn])

...

abstract public watermark (Phalcon\Image\Adapter $watermark, [mixed $offsetX], [mixed $offsetY], [mixed $opacity])

...

abstract public text (mixed $text, [mixed $offsetX], [mixed $offsetY], [mixed $opacity], [mixed $color], [mixed $size], [mixed $fontfile])

...

abstract public mask (Phalcon\Image\Adapter $watermark)

...

abstract public background (mixed $color, [mixed $opacity])

...

abstract public blur (mixed $radius)

...

abstract public pixelate (mixed $amount)

...

abstract public save ([mixed $file], [mixed $quality])

...

abstract public render ([mixed $ext], [mixed $quality])

...

Interface Phalcon\Logger\AdapterInterface

Source on GitHub

Methods

abstract public setFormatter (Phalcon\Logger\FormatterInterface $formatter)

...

abstract public getFormatter ()

...

abstract public setLogLevel (mixed $level)

...

abstract public getLogLevel ()

...

abstract public log (mixed $type, [mixed $message], [array $context])

...

abstract public begin ()

...

abstract public commit ()

...

abstract public rollback ()

...

abstract public close ()

...

abstract public debug (mixed $message, [array $context])

...

abstract public error (mixed $message, [array $context])

...

abstract public info (mixed $message, [array $context])

...

abstract public notice (mixed $message, [array $context])

...

abstract public warning (mixed $message, [array $context])

...

abstract public alert (mixed $message, [array $context])

...

abstract public emergency (mixed $message, [array $context])

...

Interface Phalcon\Logger\FormatterInterface

Source on GitHub

Methods

abstract public format (mixed $message, mixed $type, mixed $timestamp, [mixed $context])

...

Interface Phalcon\Mvc\CollectionInterface

Source on GitHub

Methods

abstract public setId (mixed $id)

...

abstract public getId ()

...

abstract public getReservedAttributes ()

...

abstract public getSource ()

...

abstract public setConnectionService (mixed $connectionService)

...

abstract public getConnection ()

...

abstract public static cloneResult (Phalcon\Mvc\CollectionInterface $collection, array $document)

...

abstract public fireEvent (mixed $eventName)

...

abstract public fireEventCancel (mixed $eventName)

...

abstract public validationHasFailed ()

...

abstract public getMessages ()

...

abstract public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

...

abstract public save ()

...

abstract public static findById (mixed $id)

...

abstract public static findFirst ([array $parameters])

...

abstract public static find ([array $parameters])

...

abstract public static count ([array $parameters])

...

abstract public delete ()

...

Interface Phalcon\Mvc\Collection\BehaviorInterface

Source on GitHub

Methods

abstract public notify (mixed $type, Phalcon\Mvc\CollectionInterface $collection)

...

abstract public missingMethod (Phalcon\Mvc\CollectionInterface $collection, mixed $method, [mixed $arguments])

...

Interface Phalcon\Mvc\Collection\ManagerInterface

Source on GitHub

Methods

abstract public setCustomEventsManager (Phalcon\Mvc\CollectionInterface $model, Phalcon\Events\ManagerInterface $eventsManager)

...

abstract public getCustomEventsManager (Phalcon\Mvc\CollectionInterface $model)

...

abstract public initialize (Phalcon\Mvc\CollectionInterface $model)

...

abstract public isInitialized (mixed $modelName)

...

abstract public getLastInitialized ()

...

abstract public setConnectionService (Phalcon\Mvc\CollectionInterface $model, mixed $connectionService)

...

abstract public useImplicitObjectIds (Phalcon\Mvc\CollectionInterface $model, mixed $useImplicitObjectIds)

...

abstract public isUsingImplicitObjectIds (Phalcon\Mvc\CollectionInterface $model)

...

abstract public getConnection (Phalcon\Mvc\CollectionInterface $model)

...

abstract public notifyEvent (mixed $eventName, Phalcon\Mvc\CollectionInterface $model)

...

abstract public addBehavior (Phalcon\Mvc\CollectionInterface $model, Phalcon\Mvc\Collection\BehaviorInterface $behavior)

...

Interface Phalcon\Mvc\ControllerInterface

Source on GitHub

Interface Phalcon\Mvc\Controller\BindModelInterface

Source on GitHub

Methods

abstract public static getModelName ()

...

Interface Phalcon\Mvc\DispatcherInterface

implements Phalcon\DispatcherInterface

Source on GitHub

Methods

abstract public setControllerSuffix (mixed $controllerSuffix)

...

abstract public setDefaultController (mixed $controllerName)

...

abstract public setControllerName (mixed $controllerName)

...

abstract public getControllerName ()

...

abstract public getLastController ()

...

abstract public getActiveController ()

...

abstract public setActionSuffix (mixed $actionSuffix) inherited from Phalcon\DispatcherInterface

...

abstract public getActionSuffix () inherited from Phalcon\DispatcherInterface

...

abstract public setDefaultNamespace (mixed $defaultNamespace) inherited from Phalcon\DispatcherInterface

...

abstract public setDefaultAction (mixed $actionName) inherited from Phalcon\DispatcherInterface

...

abstract public setNamespaceName (mixed $namespaceName) inherited from Phalcon\DispatcherInterface

...

abstract public setModuleName (mixed $moduleName) inherited from Phalcon\DispatcherInterface

...

abstract public setActionName (mixed $actionName) inherited from Phalcon\DispatcherInterface

...

abstract public getActionName () inherited from Phalcon\DispatcherInterface

...

abstract public setParams (mixed $params) inherited from Phalcon\DispatcherInterface

...

abstract public getParams () inherited from Phalcon\DispatcherInterface

...

abstract public setParam (mixed $param, mixed $value) inherited from Phalcon\DispatcherInterface

...

abstract public getParam (mixed $param, [mixed $filters]) inherited from Phalcon\DispatcherInterface

...

abstract public hasParam (mixed $param) inherited from Phalcon\DispatcherInterface

...

abstract public isFinished () inherited from Phalcon\DispatcherInterface

...

abstract public getReturnedValue () inherited from Phalcon\DispatcherInterface

...

abstract public dispatch () inherited from Phalcon\DispatcherInterface

...

abstract public forward (mixed $forward) inherited from Phalcon\DispatcherInterface

...

Interface Phalcon\Mvc\EntityInterface

Source on GitHub

Methods

abstract public readAttribute (mixed $attribute)

...

abstract public writeAttribute (mixed $attribute, mixed $value)

...

Interface Phalcon\Mvc\Micro\CollectionInterface

Source on GitHub

Methods

abstract public setPrefix (mixed $prefix)

...

abstract public getPrefix ()

...

abstract public getHandlers ()

...

abstract public setHandler (mixed $handler, [mixed $lazy])

...

abstract public setLazy (mixed $lazy)

...

abstract public isLazy ()

...

abstract public getHandler ()

...

abstract public map (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public get (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public post (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public put (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public patch (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public head (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public delete (mixed $routePattern, mixed $handler, [mixed $name])

...

abstract public options (mixed $routePattern, mixed $handler, [mixed $name])

...

Interface Phalcon\Mvc\Micro\MiddlewareInterface

Source on GitHub

Methods

abstract public call (Phalcon\Mvc\Micro $application)

...

Interface Phalcon\Mvc\ModelInterface

Source on GitHub

Methods

abstract public setTransaction (Phalcon\Mvc\Model\TransactionInterface $transaction)

...

abstract public getSource ()

...

abstract public getSchema ()

...

abstract public setConnectionService (mixed $connectionService)

...

abstract public setWriteConnectionService (mixed $connectionService)

...

abstract public setReadConnectionService (mixed $connectionService)

...

abstract public getReadConnectionService ()

...

abstract public getWriteConnectionService ()

...

abstract public getReadConnection ()

...

abstract public getWriteConnection ()

...

abstract public setDirtyState (mixed $dirtyState)

...

abstract public getDirtyState ()

...

abstract public assign (array $data, [mixed $dataColumnMap], [mixed $whiteList])

...

abstract public static cloneResultMap (mixed $base, array $data, mixed $columnMap, [mixed $dirtyState], [mixed $keepSnapshots])

...

abstract public static cloneResult (Phalcon\Mvc\ModelInterface $base, array $data, [mixed $dirtyState])

...

abstract public static cloneResultMapHydrate (array $data, mixed $columnMap, mixed $hydrationMode)

...

abstract public static find ([mixed $parameters])

...

abstract public static findFirst ([mixed $parameters])

...

abstract public static query ([Phalcon\DiInterface $dependencyInjector])

...

abstract public static count ([mixed $parameters])

...

abstract public static sum ([mixed $parameters])

...

abstract public static maximum ([mixed $parameters])

...

abstract public static minimum ([mixed $parameters])

...

abstract public static average ([mixed $parameters])

...

abstract public fireEvent (mixed $eventName)

...

abstract public fireEventCancel (mixed $eventName)

...

abstract public appendMessage (Phalcon\Mvc\Model\MessageInterface $message)

...

abstract public validationHasFailed ()

...

abstract public getMessages ()

...

abstract public save ([mixed $data], [mixed $whiteList])

...

abstract public create ([mixed $data], [mixed $whiteList])

...

abstract public update ([mixed $data], [mixed $whiteList])

...

abstract public delete ()

...

abstract public getOperationMade ()

...

abstract public refresh ()

...

abstract public skipOperation (mixed $skip)

...

abstract public getRelated (mixed $alias, [mixed $arguments])

...

abstract public setSnapshotData (array $data, [mixed $columnMap])

...

abstract public reset ()

...

Interface Phalcon\Mvc\Model\BehaviorInterface

Source on GitHub

Methods

abstract public notify (mixed $type, Phalcon\Mvc\ModelInterface $model)

...

abstract public missingMethod (Phalcon\Mvc\ModelInterface $model, mixed $method, [mixed $arguments])

...

Interface Phalcon\Mvc\Model\CriteriaInterface

Source on GitHub

Methods

abstract public setModelName (mixed $modelName)

...

abstract public getModelName ()

...

abstract public bind (array $bindParams)

...

abstract public bindTypes (array $bindTypes)

...

abstract public where (mixed $conditions)

...

abstract public conditions (mixed $conditions)

...

abstract public orderBy (mixed $orderColumns)

...

abstract public limit (mixed $limit, [mixed $offset])

...

abstract public forUpdate ([mixed $forUpdate])

...

abstract public sharedLock ([mixed $sharedLock])

...

abstract public andWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

...

abstract public orWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

...

abstract public betweenWhere (mixed $expr, mixed $minimum, mixed $maximum)

...

abstract public notBetweenWhere (mixed $expr, mixed $minimum, mixed $maximum)

...

abstract public inWhere (mixed $expr, array $values)

...

abstract public notInWhere (mixed $expr, array $values)

...

abstract public getWhere ()

...

abstract public getConditions ()

...

abstract public getLimit ()

...

abstract public getOrderBy ()

...

abstract public getParams ()

...

abstract public execute ()

...

Interface Phalcon\Mvc\Model\ManagerInterface

Source on GitHub

Methods

abstract public initialize (Phalcon\Mvc\ModelInterface $model)

...

abstract public setModelSource (Phalcon\Mvc\ModelInterface $model, mixed $source)

...

abstract public getModelSource (Phalcon\Mvc\ModelInterface $model)

...

abstract public setModelSchema (Phalcon\Mvc\ModelInterface $model, mixed $schema)

...

abstract public getModelSchema (Phalcon\Mvc\ModelInterface $model)

...

abstract public setConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

...

abstract public setReadConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

...

abstract public getReadConnectionService (Phalcon\Mvc\ModelInterface $model)

...

abstract public setWriteConnectionService (Phalcon\Mvc\ModelInterface $model, mixed $connectionService)

...

abstract public getWriteConnectionService (Phalcon\Mvc\ModelInterface $model)

...

abstract public getReadConnection (Phalcon\Mvc\ModelInterface $model)

...

abstract public getWriteConnection (Phalcon\Mvc\ModelInterface $model)

...

abstract public isInitialized (mixed $modelName)

...

abstract public getLastInitialized ()

...

abstract public load (mixed $modelName, [mixed $newInstance])

...

abstract public addHasOne (Phalcon\Mvc\ModelInterface $model, mixed $fields, mixed $referencedModel, mixed $referencedFields, [mixed $options])

...

abstract public addBelongsTo (Phalcon\Mvc\ModelInterface $model, mixed $fields, mixed $referencedModel, mixed $referencedFields, [mixed $options])

...

abstract public addHasMany (Phalcon\Mvc\ModelInterface $model, mixed $fields, mixed $referencedModel, mixed $referencedFields, [mixed $options])

...

abstract public existsBelongsTo (mixed $modelName, mixed $modelRelation)

...

abstract public existsHasMany (mixed $modelName, mixed $modelRelation)

...

abstract public existsHasOne (mixed $modelName, mixed $modelRelation)

...

abstract public getBelongsToRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

...

abstract public getHasManyRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

...

abstract public getHasOneRecords (mixed $method, mixed $modelName, mixed $modelRelation, Phalcon\Mvc\ModelInterface $record, [mixed $parameters])

...

abstract public getBelongsTo (Phalcon\Mvc\ModelInterface $model)

...

abstract public getHasMany (Phalcon\Mvc\ModelInterface $model)

...

abstract public getHasOne (Phalcon\Mvc\ModelInterface $model)

...

abstract public getHasOneAndHasMany (Phalcon\Mvc\ModelInterface $model)

...

abstract public getRelations (mixed $modelName)

...

abstract public getRelationsBetween (mixed $first, mixed $second)

...

abstract public createQuery (mixed $phql)

...

abstract public executeQuery (mixed $phql, [mixed $placeholders])

...

abstract public createBuilder ([mixed $params])

...

abstract public addBehavior (Phalcon\Mvc\ModelInterface $model, Phalcon\Mvc\Model\BehaviorInterface $behavior)

...

abstract public notifyEvent (mixed $eventName, Phalcon\Mvc\ModelInterface $model)

...

abstract public missingMethod (Phalcon\Mvc\ModelInterface $model, mixed $eventName, mixed $data)

...

abstract public getLastQuery ()

...

abstract public getRelationByAlias (mixed $modelName, mixed $alias)

...

Interface Phalcon\Mvc\Model\MessageInterface

Source on GitHub

Methods

abstract public setType (mixed $type)

...

abstract public getType ()

...

abstract public setMessage (mixed $message)

...

abstract public getMessage ()

...

abstract public setField (mixed $field)

...

abstract public getField ()

...

abstract public __toString ()

...

abstract public static __set_state (array $message)

...

Interface Phalcon\Mvc\Model\MetaDataInterface

Source on GitHub

Methods

abstract public setStrategy (Phalcon\Mvc\Model\MetaData\StrategyInterface $strategy)

...

abstract public getStrategy ()

...

abstract public readMetaData (Phalcon\Mvc\ModelInterface $model)

...

abstract public readMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index)

...

abstract public writeMetaDataIndex (Phalcon\Mvc\ModelInterface $model, mixed $index, mixed $data)

...

abstract public readColumnMap (Phalcon\Mvc\ModelInterface $model)

...

abstract public readColumnMapIndex (Phalcon\Mvc\ModelInterface $model, mixed $index)

...

abstract public getAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getNonPrimaryKeyAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getNotNullAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getDataTypes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getDataTypesNumeric (Phalcon\Mvc\ModelInterface $model)

...

abstract public getIdentityField (Phalcon\Mvc\ModelInterface $model)

...

abstract public getBindTypes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public setAutomaticCreateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

...

abstract public setAutomaticUpdateAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

...

abstract public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)

...

abstract public getEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model)

...

abstract public getDefaultValues (Phalcon\Mvc\ModelInterface $model)

...

abstract public getColumnMap (Phalcon\Mvc\ModelInterface $model)

...

abstract public getReverseColumnMap (Phalcon\Mvc\ModelInterface $model)

...

abstract public hasAttribute (Phalcon\Mvc\ModelInterface $model, mixed $attribute)

...

abstract public isEmpty ()

...

abstract public reset ()

...

abstract public read (mixed $key)

...

abstract public write (mixed $key, mixed $data)

...

Interface Phalcon\Mvc\Model\MetaData\StrategyInterface

Source on GitHub

Methods

abstract public getMetaData (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

...

abstract public getColumnMaps (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)

...

Interface Phalcon\Mvc\Model\QueryInterface

Source on GitHub

Methods

abstract public parse ()

...

abstract public cache (mixed $cacheOptions)

...

abstract public getCacheOptions ()

...

abstract public setUniqueRow (mixed $uniqueRow)

...

abstract public getUniqueRow ()

...

abstract public execute ([mixed $bindParams], [mixed $bindTypes])

...

Interface Phalcon\Mvc\Model\Query\BuilderInterface

Source on GitHub

Constants

string OPERATOR_OR

string OPERATOR_AND

Methods

abstract public columns (mixed $columns)

...

abstract public getColumns ()

...

abstract public from (mixed $models)

...

abstract public addFrom (mixed $model, [mixed $alias])

...

abstract public getFrom ()

...

abstract public join (mixed $model, [mixed $conditions], [mixed $alias])

...

abstract public innerJoin (mixed $model, [mixed $conditions], [mixed $alias])

...

abstract public leftJoin (mixed $model, [mixed $conditions], [mixed $alias])

...

abstract public rightJoin (mixed $model, [mixed $conditions], [mixed $alias])

...

abstract public getJoins ()

...

abstract public where (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

...

abstract public andWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

...

abstract public orWhere (mixed $conditions, [mixed $bindParams], [mixed $bindTypes])

...

abstract public betweenWhere (mixed $expr, mixed $minimum, mixed $maximum, [mixed $operator])

...

abstract public notBetweenWhere (mixed $expr, mixed $minimum, mixed $maximum, [mixed $operator])

...

abstract public inWhere (mixed $expr, array $values, [mixed $operator])

...

abstract public notInWhere (mixed $expr, array $values, [mixed $operator])

...

abstract public getWhere ()

...

abstract public orderBy (mixed $orderBy)

...

abstract public getOrderBy ()

...

abstract public having (mixed $having)

...

abstract public getHaving ()

...

abstract public limit (mixed $limit, [mixed $offset])

...

abstract public getLimit ()

...

abstract public groupBy (mixed $group)

...

abstract public getGroupBy ()

...

abstract public getPhql ()

...

abstract public getQuery ()

...

Interface Phalcon\Mvc\Model\Query\StatusInterface

Source on GitHub

Methods

abstract public getModel ()

...

abstract public getMessages ()

...

abstract public success ()

...

Interface Phalcon\Mvc\Model\RelationInterface

Source on GitHub

Methods

abstract public setIntermediateRelation (mixed $intermediateFields, mixed $intermediateModel, mixed $intermediateReferencedFields)

...

abstract public isReusable ()

...

abstract public getType ()

...

abstract public getReferencedModel ()

...

abstract public getFields ()

...

abstract public getReferencedFields ()

...

abstract public getOptions ()

...

abstract public getOption (mixed $name)

...

abstract public isForeignKey ()

...

abstract public getForeignKey ()

...

abstract public isThrough ()

...

abstract public getIntermediateFields ()

...

abstract public getIntermediateModel ()

...

abstract public getIntermediateReferencedFields ()

...

Interface Phalcon\Mvc\Model\ResultInterface

Source on GitHub

Methods

abstract public setDirtyState (mixed $dirtyState)

...

Interface Phalcon\Mvc\Model\ResultsetInterface

Source on GitHub

Methods

abstract public getType ()

...

abstract public getFirst ()

...

abstract public getLast ()

...

abstract public setIsFresh (mixed $isFresh)

...

abstract public isFresh ()

...

abstract public getCache ()

...

abstract public toArray ()

...

Interface Phalcon\Mvc\Model\TransactionInterface

Source on GitHub

Methods

abstract public setTransactionManager (Phalcon\Mvc\Model\Transaction\ManagerInterface $manager)

...

abstract public begin ()

...

abstract public commit ()

...

abstract public rollback ([mixed $rollbackMessage], [mixed $rollbackRecord])

...

abstract public getConnection ()

...

abstract public setIsNewTransaction (mixed $isNew)

...

abstract public setRollbackOnAbort (mixed $rollbackOnAbort)

...

abstract public isManaged ()

...

abstract public getMessages ()

...

abstract public isValid ()

...

abstract public setRollbackedRecord (Phalcon\Mvc\ModelInterface $record)

...

Interface Phalcon\Mvc\Model\Transaction\ManagerInterface

Source on GitHub

Methods

abstract public has ()

...

abstract public get ([mixed $autoBegin])

...

abstract public rollbackPendent ()

...

abstract public commit ()

...

abstract public rollback ([mixed $collect])

...

abstract public notifyRollback (Phalcon\Mvc\Model\TransactionInterface $transaction)

...

abstract public notifyCommit (Phalcon\Mvc\Model\TransactionInterface $transaction)

...

abstract public collectTransactions ()

...

Interface Phalcon\Mvc\Model\ValidatorInterface

Source on GitHub

Methods

abstract public getMessages ()

...

abstract public validate (Phalcon\Mvc\EntityInterface $record)

...

Interface Phalcon\Mvc\ModuleDefinitionInterface

Source on GitHub

Methods

abstract public registerAutoloaders ([Phalcon\DiInterface $dependencyInjector])

...

abstract public registerServices (Phalcon\DiInterface $dependencyInjector)

...

Interface Phalcon\Mvc\RouterInterface

Source on GitHub

Methods

abstract public setDefaultModule (mixed $moduleName)

...

abstract public setDefaultController (mixed $controllerName)

...

abstract public setDefaultAction (mixed $actionName)

...

abstract public setDefaults (array $defaults)

...

abstract public handle ([mixed $uri])

...

abstract public add (mixed $pattern, [mixed $paths], [mixed $httpMethods])

...

abstract public addGet (mixed $pattern, [mixed $paths])

...

abstract public addPost (mixed $pattern, [mixed $paths])

...

abstract public addPut (mixed $pattern, [mixed $paths])

...

abstract public addPatch (mixed $pattern, [mixed $paths])

...

abstract public addDelete (mixed $pattern, [mixed $paths])

...

abstract public addOptions (mixed $pattern, [mixed $paths])

...

abstract public addHead (mixed $pattern, [mixed $paths])

...

abstract public addPurge (mixed $pattern, [mixed $paths])

...

abstract public addTrace (mixed $pattern, [mixed $paths])

...

abstract public addConnect (mixed $pattern, [mixed $paths])

...

abstract public mount (Phalcon\Mvc\Router\GroupInterface $group)

...

abstract public clear ()

...

abstract public getModuleName ()

...

abstract public getNamespaceName ()

...

abstract public getControllerName ()

...

abstract public getActionName ()

...

abstract public getParams ()

...

abstract public getMatchedRoute ()

...

abstract public getMatches ()

...

abstract public wasMatched ()

...

abstract public getRoutes ()

...

abstract public getRouteById (mixed $id)

...

abstract public getRouteByName (mixed $name)

...

Interface Phalcon\Mvc\Router\GroupInterface

Source on GitHub

Methods

abstract public setHostname (mixed $hostname)

...

abstract public getHostname ()

...

abstract public setPrefix (mixed $prefix)

...

abstract public getPrefix ()

...

abstract public beforeMatch (mixed $beforeMatch)

...

abstract public getBeforeMatch ()

...

abstract public setPaths (mixed $paths)

...

abstract public getPaths ()

...

abstract public getRoutes ()

...

abstract public add (mixed $pattern, [mixed $paths], [mixed $httpMethods])

...

abstract public addGet (mixed $pattern, [mixed $paths])

...

abstract public addPost (mixed $pattern, [mixed $paths])

...

abstract public addPut (mixed $pattern, [mixed $paths])

...

abstract public addPatch (mixed $pattern, [mixed $paths])

...

abstract public addDelete (mixed $pattern, [mixed $paths])

...

abstract public addOptions (mixed $pattern, [mixed $paths])

...

abstract public addHead (mixed $pattern, [mixed $paths])

...

abstract public clear ()

...

Interface Phalcon\Mvc\Router\RouteInterface

Source on GitHub

Methods

abstract public setHostname (mixed $hostname)

...

abstract public getHostname ()

...

abstract public compilePattern (mixed $pattern)

...

abstract public via (mixed $httpMethods)

...

abstract public reConfigure (mixed $pattern, [mixed $paths])

...

abstract public getName ()

...

abstract public setName (mixed $name)

...

abstract public setHttpMethods (mixed $httpMethods)

...

abstract public getRouteId ()

...

abstract public getPattern ()

...

abstract public getCompiledPattern ()

...

abstract public getPaths ()

...

abstract public getReversedPaths ()

...

abstract public getHttpMethods ()

...

abstract public static reset ()

...

Interface Phalcon\Mvc\UrlInterface

Source on GitHub

Methods

abstract public setBaseUri (mixed $baseUri)

...

abstract public getBaseUri ()

...

abstract public setBasePath (mixed $basePath)

...

abstract public getBasePath ()

...

abstract public get ([mixed $uri], [mixed $args], [mixed $local])

...

abstract public path ([mixed $path])

...

Interface Phalcon\Mvc\ViewBaseInterface

Source on GitHub

Methods

abstract public setViewsDir (mixed $viewsDir)

...

abstract public getViewsDir ()

...

abstract public setParamToView (mixed $key, mixed $value)

...

abstract public setVar (mixed $key, mixed $value)

...

abstract public getParamsToView ()

...

abstract public getCache ()

...

abstract public cache ([mixed $options])

...

abstract public setContent (mixed $content)

...

abstract public getContent ()

...

abstract public partial (mixed $partialPath, [mixed $params])

...

Interface Phalcon\Mvc\ViewInterface

implements Phalcon\Mvc\ViewBaseInterface

Source on GitHub

Methods

abstract public setLayoutsDir (mixed $layoutsDir)

...

abstract public getLayoutsDir ()

...

abstract public setPartialsDir (mixed $partialsDir)

...

abstract public getPartialsDir ()

...

abstract public setBasePath (mixed $basePath)

...

abstract public getBasePath ()

...

abstract public setRenderLevel (mixed $level)

...

abstract public setMainView (mixed $viewPath)

...

abstract public getMainView ()

...

abstract public setLayout (mixed $layout)

...

abstract public getLayout ()

...

abstract public setTemplateBefore (mixed $templateBefore)

...

abstract public cleanTemplateBefore ()

...

abstract public setTemplateAfter (mixed $templateAfter)

...

abstract public cleanTemplateAfter ()

...

abstract public getControllerName ()

...

abstract public getActionName ()

...

abstract public getParams ()

...

abstract public start ()

...

abstract public registerEngines (array $engines)

...

abstract public render (mixed $controllerName, mixed $actionName, [mixed $params])

...

abstract public pick (mixed $renderView)

...

abstract public finish ()

...

abstract public getActiveRenderPath ()

...

abstract public disable ()

...

abstract public enable ()

...

abstract public reset ()

...

abstract public isDisabled ()

...

abstract public setViewsDir (mixed $viewsDir) inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public getViewsDir () inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public setParamToView (mixed $key, mixed $value) inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public setVar (mixed $key, mixed $value) inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public getParamsToView () inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public getCache () inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public cache ([mixed $options]) inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public setContent (mixed $content) inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public getContent () inherited from Phalcon\Mvc\ViewBaseInterface

...

abstract public partial (mixed $partialPath, [mixed $params]) inherited from Phalcon\Mvc\ViewBaseInterface

...

Interface Phalcon\Mvc\View\EngineInterface

Source on GitHub

Methods

abstract public getContent ()

...

abstract public partial (mixed $partialPath, [mixed $params])

...

abstract public render (mixed $path, mixed $params, [mixed $mustClean])

...

Interface Phalcon\Paginator\AdapterInterface

Source on GitHub

Methods

abstract public setCurrentPage (mixed $page)

...

abstract public getPaginate ()

...

abstract public setLimit (mixed $limit)

...

abstract public getLimit ()

...

Interface Phalcon\Session\AdapterInterface

Source on GitHub

Methods

abstract public start ()

...

abstract public setOptions (array $options)

...

abstract public getOptions ()

...

abstract public get (mixed $index, [mixed $defaultValue])

...

abstract public set (mixed $index, mixed $value)

...

abstract public has (mixed $index)

...

abstract public remove (mixed $index)

...

abstract public getId ()

...

abstract public isStarted ()

...

abstract public destroy ([mixed $removeData])

...

abstract public regenerateId ([mixed $deleteOldSession])

...

abstract public setName (mixed $name)

...

abstract public getName ()

...

Interface Phalcon\Session\BagInterface

Source on GitHub

Methods

abstract public initialize ()

...

abstract public destroy ()

...

abstract public set (mixed $property, mixed $value)

...

abstract public get (mixed $property, [mixed $defaultValue])

...

abstract public has (mixed $property)

...

abstract public __set (mixed $property, mixed $value)

...

abstract public __get (mixed $property)

...

abstract public __isset (mixed $property)

...

Interface Phalcon\Translate\AdapterInterface

Source on GitHub

Methods

abstract public t (mixed $translateKey, [mixed $placeholders])

...

abstract public query (mixed $index, [mixed $placeholders])

...

abstract public exists (mixed $index)

...

Interface Phalcon\Translate\InterpolatorInterface

Source on GitHub

Methods

abstract public replacePlaceholders (mixed $translation, [mixed $placeholders])

...

Interface Phalcon\ValidationInterface

Source on GitHub

Methods

abstract public validate ([mixed $data], [mixed $entity])

...

abstract public add (mixed $field, Phalcon\Validation\ValidatorInterface $validator)

...

abstract public rule (mixed $field, Phalcon\Validation\ValidatorInterface $validator)

...

abstract public rules (mixed $field, array $validators)

...

abstract public setFilters (mixed $field, mixed $filters)

...

abstract public getFilters ([mixed $field])

...

abstract public getValidators ()

...

abstract public getEntity ()

...

abstract public setDefaultMessages ([array $messages])

...

abstract public getDefaultMessage (mixed $type)

...

abstract public getMessages ()

...

abstract public setLabels (array $labels)

...

abstract public getLabel (mixed $field)

...

abstract public appendMessage (Phalcon\Validation\MessageInterface $message)

...

abstract public bind (mixed $entity, mixed $data)

...

abstract public getValue (mixed $field)

...

Interface Phalcon\Validation\MessageInterface

Source on GitHub

Methods

abstract public setType (mixed $type)

...

abstract public getType ()

...

abstract public setMessage (mixed $message)

...

abstract public getMessage ()

...

abstract public setField (mixed $field)

...

abstract public getField ()

...

abstract public __toString ()

...

abstract public static __set_state (array $message)

...

Interface Phalcon\Validation\ValidatorInterface

Source on GitHub

Methods

abstract public hasOption (mixed $key)

...

abstract public getOption (mixed $key, [mixed $defaultValue])

...

abstract public validate (Phalcon\Validation $validation, mixed $attribute)

...

声明

授权(License)

Phalcon is brought to you by the Phalcon Team! [Twitter - Google Plus - Github]

The Phalcon PHP Framework is released under the new BSD license. Except where otherwise noted, content on this site is licensed under the Creative Commons Attribution 3.0 License.

If you love Phalcon please return something to the community! :)

旧的版本

  • 2.0.0 <https://docs.phalconphp.com/zh/2.0.0/>

其他格式

Follow along: