目次
|
ようこそ¶新しいアプローチで作られたPHPフレームワーク、Phalconへようこそ。 我々の使命は、パフォーマンスを気にせずにウェブサイトやアプリケーションを開発できる、先進的なツールを提供することです。 Phalconとは¶Phalconは、C拡張として実装され、ハイパフォーマンスに最適化された、オープンソースのPHP5向けのフルスタックフレームワークです。 機能は、使いやすいようにPHPクラスとして実装されているため、C言語を覚えたり使用する必要はありません。 さらに、Phalconは疎結合になっているため、オブジェクトをあなたのアプリケーションの必要に応じて、コンポーネントとして利用することができます。 Phalconはパフォーマンスだけではありません。我々のゴールは、それを堅牢かつ高機能で使いやすいものにすることです! 目次¶インストール¶インストール¶PHP 拡張モジュールは、従来の PHP ベースのライブラリやフレームワークとは若干異なるインストール方法をとります。 あなたのシステム向けのバイナリパッケージをダウンロードするか、ソースコードからビルドする2つの方法があります。 Windows¶Windows 上で Phalcon を使用するには、DLLライブラリをダウンロードします。そして php.ini を編集し、最後に次の行を追加します。 extension=php_phalcon.dll
最後に WEB サーバーを再起動します。 次のスクリーンキャストは、Windows 上に Phalcon をインストールするステップバイステップガイドです。 関連ガイド¶XAMPPはApache、MySQL、PHP、Perlを簡単にインストールできます。 まず、XAMPPをダウンロードし、解凍を行い、起動させます。 以下では、Windows版XAMPPを使用する場合のPhalconのインストール方法を記載しています。 XAMPPは最新のバージョンを使用するようにしてください。 XAMPPでは、32 bitバージョンのApache、PHPを使用しています。 Windows版Phalconのx86 バージョンをダウンロードする必要があります。 Phalconライブラリをダウンロードすると、以下のようなzipファイルがあるはずです。 ![]() アーカイブを解凍し、Phalcon DLLがあるか確認してください。 ![]() PHPエクステンションにphp_phalcon.dllをコピーしてください。 C:\xampp folder にXAMPPがインストールされている場合、エクステンションのパスは、C:\xampp\php\ext となっているはずです。 ![]() C:\xampp\php\php.ini にあるphp.iniファイルをテキストエディタなどで編集します。 ファイルの最後に extension=php_phalcon.dll を追記し保存します。 ![]() XAMPPコントロールセンターからApacheを再起動させます。 新しいPHP設定が読み込まれるはずです。 ![]() ブラウザでhttp://localhostを開くと、XAMPPのウェルカムページが表示されると思います。 そしたら、phpinfo()のリンクをクリックして開きます。 ![]() phpinfo()で、phalconエクステンションがロードされているか確認します。 ![]() phpinfo()でphalconのバージョンが表示されていれば、インストール成功です! 以下では、Windows版Phalconのインストール手順を説明しています。 WampServerは、Windowsのweb開発環境ツールです。 ウェブアプリケーションをApache2、PHP、MySQLで作成できます。 以下では、Windows版WampServerを使用する場合のPhalconのインストール方法を記載しています。 WampServerは最新のバージョンを使用するようにしてください。 WAMPは32 bitと64 bitの両方のバージョンがあります。 自身の環境にあったWindows版Phalconをダウンロードしてください。 Phalconライブラリをダウンロードすると、以下のようなzipファイルがあるはずです。 ![]() アーカイブを解凍し、Phalcon DLLがあるか確認してください。 ![]() PHPエクステンションにphp_phalcon.dllをコピーしてください。 C:\wamp folder にXAMPPがインストールされている場合、エクステンションのパスは、C:\wamp\bin\php\php5.5.12\ext となっているはずです。 ![]() C:\wamp\bin\php\php5.5.12\php.ini にあるphp.iniファイルをテキストエディタなどで編集します。 ファイルの最後に extension=php_phalcon.dll を追記し保存します。 また、C:\wamp\bin\apache\apache2.4.9\bin\php.ini こちらにもphp.iniがある場合があります。 ![]() Also edit another php.ini file, which is located at C:\wamp\bin\apache\apache2.4.9\bin\php.ini. Append at the end of the file: extension=php_phalcon.dll and save it. Apacheを再起動させます。 Do a single click on the WampServer icon at system tray. Choose “Restart All Services” from the pop-up menu. Check out that tray icon will become green again. ![]() ブラウザでhttp://localhostを開くと、WAMPのウェルカムページが表示されると思います。 そしたら、phpinfo()のリンクをクリックして開きます。 ![]() Congrats!, You are now flying with 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
この作業は、あなたがディストリビューションを変更したり安定板とナイトリーを選び直すといった事情がなければ、実施は一度だけしか必要ありません。 Phalcon をインストールするには: sudo apt-get install php5-phalcon
# PHP 7 の場合
sudo apt-get install php7.0-phalcon
RPM ディストリビューション (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
この作業は、あなたがディストリビューションを変更したり安定板とナイトリーを選び直すといった事情がなければ、実施は一度だけしか必要ありません。 Phalcon をインストールするには: sudo yum install php56u-phalcon
# PHP 7 の場合
ソースからコンパイルする¶Linux/Solaris の環境では、簡単に拡張モジュールをソースコードからコンパイルしてインストールすることができます。 必要となるパッケージは次の通りです:
一般的なプラットフォームにおける具体的なパッケージ: # 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.ini に拡張モジュールを追加します。 # Suse の場合: /etc/php5/conf.d/ に下記内容が書いてある phalcon.ini を追加します:
extension=phalcon.so
# CentOS/RedHat/Fedora の場合: /etc/php.d/ に下記内容が書いてある phalcon.ini を追加します:
extension=phalcon.so
# Ubuntu/Debian、Apache2 で構成している場合: /etc/php5/apache2/conf.d/ に、下記内容の 30-phalcon.ini を追加します:
extension=phalcon.so
# Ubuntu/Debian、php5-fpm で構成している場合: /etc/php5/fpm/conf.d/ に、下記内容の 30-phalcon.ini を追加します:
extension=phalcon.so
# Ubuntu/Debian、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¶macOS, OS X システムではソースコードからコンパイル、そしてインストールすることができます: 前提条件¶必須パッケージは下記の通り:
# 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 では port を利用することができます。インストールするには、次のシンプルなコマンドを叩くだけです。 pkg_add -r phalcon
または export CFLAGS="-O2 --fvisibility=hidden"
cd /usr/ports/www/phalcon
make install clean
インストールの確認¶
<?php print_r(get_loaded_extensions()); ?>
Phalcon 拡張モジュールは下記のように出力の一部に現れるでしょう。 Array
(
[0] => Core
[1] => libxml
[2] => filter
[3] => SPL
[4] => standard
[5] => phalcon
[6] => pdo_mysql
)
インストール ノート¶各 WEB サーバーにおけるインストールノート Apache インストール ノート¶Apache は多くのプラットフォームで利用可能な、人気のあるWebサーバーです。 次の設定は、 PhalconをApacheで使う際の設定例です。ここでは主に、使いやすいURLと router component. を 使用できるようにmod_rewriteモジュールを設定する方法についてフォーカスしています。 一般的にアプリケーションは下記のような構造になります。 test/
app/
controllers/
models/
views/
public/
css/
img/
js/
index.php
これは最も一般的なケースで、アプリケーションはドキュメントルート下の任意のディレクトリにインストールされています。 このケースでは、2つの .htaccess ファイルを使います。1つめはアプリケーションコードを隠すためにすべてのリクエストを アプリケーションのドキュメントルート (public/) へリダイレクトします。 # test/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule ((?s).*) public/$1 [L]
</IfModule>
2つめの .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>
そしてこの2つめの設定では、Virtual Host 内に 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 は無料でオープンソースな高性能HTTPサーバで、リバースプロキシとしてだけでなく、IMAP/POP3のプロキシサーバとしても動きます。 伝統的なサーバとは異なり、Nginx は要求を処理するスレッドに依存しません。 その代わりに、はるかに拡張性の高いイベント駆動型(非同期)アーキテクチャを使用しています。 このアーキテクチャは、使用メモリが少ないのですが、より重要なのは、負荷の下でもメモリ消費量が予測可能だということです。 PHP-FPM (FastCGI Process Manager) は Nginx がPHPファイルを処理できるようにするために、通常使われます。 最近、PHP-FPM はいくつかのUNIXのPHPのディストリビューションにバンドルされています。Phalcon + Nginx + PHP-FPM は、PHPアプリケーションのための最大のパフォーマンスを提供する協力なツールセットになります。 以下は、Phalconをnginxで使用できるようにする設定です。
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 {
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 は高パフォーマンスのWebサーバーです。非常に高速かつ柔軟で、設定も簡単です。 Cherokee はWebサーバで設定可能なほぼ全ての設定を構成するための、使いやすいグラフィカルインターフェースを提供します。rootで /path-to-cherokee/sbin/cherokee-admin を実行して、Cherokee administratorを起動してください。: ![]() 「vServers」をクリックして、新しいバーチャルホストを作成し、新しい仮想サーバーを追加してください。: ![]() 最近追加した仮想サーバーが、画面上の左のバーに表示されるはずです。「Behaviors」タブで、仮想サーバーのデフォルトのビヘイビアを見ることができます。「Rule Management」ボタンをクリックし、「Directory /cherokee_themes」と「Directory /icons」を削除します: ![]() ウィザードに従って、PHP言語のビヘイビアを追加します。このビヘイビアによって、PHPアプリケーションを実行できるようになります。: ![]() 通常、このビヘイビアには追加の設定は必要ありません。もう1つビヘイビアを追加しましょう。今度は「Manual Configuration」セクションの「Rule Type」で、「File Exists」を選択し、「Match any file」が有効になっていることを確認してください。: ![]() 「Handler」タブで、「List & Send」をハンドラーとして選択します。: ![]() URLのリライトエンジンを有効化するため、「Default」ビヘイビアを編集します。ハンドラーを「Redirection」に変更し、「^(.*)$」という正規表現をエンジンに追加します。: ![]() 最後に、ビヘイビアが次の順番になっていることを確認してください: ![]() ブラウザでアプリケーションを実行します: ![]() PHP ビルトインサーバーの利用¶PHP5.4.0 以降では、PHP の組み込みの Web サーバーを開発用に使うことができます。 サーバーを起動するには、以下のコマンドを打ち込んでください: php -S localhost:8000 -t /public
index.php に渡される URI を書き換えたいなら、以下のルーターファイル(.htrouter.php)を使用してください。 <?php
if (!file_exists(__DIR__ . '/' . $_SERVER['REQUEST_URI'])) {
$_GET['_url'] = $_SERVER['REQUEST_URI'];
}
return false;
次に、以下のコマンドでサーバーを起動します: php -S localhost:8000 -t /public .htrouter.php
ブラウザで http://localhost:8000/ にアクセスし、正常に動作していることを確認してください。 Phalcon 開発者ツール¶These tools are a collection of useful scripts to generate skeleton code. Core components of your application can be generated with a simple command, allowing you to easily develop applications using Phalcon.
ダウンロード¶You can download or clone a cross platform package containing the developer tools from Github. インストール¶These are detailed instructions on how to install the developer tools on different platforms: 下記のステップは Windows に Phalcon 開発者ツールのインストールするための手順を示すものです。 Download セクションで、開発者ツールを同梱したクロスプラットフォームのパッケージがダウンロードできます。また、Github から clone でもできます。 Windows プラットフォームでは、システム環境変数 PATH に、Phalcon と PHP の実行ファイルの場所を含むよう構成する必要があります。 開発者ツールを ZIP 書庫でダウンロードした場合は、 c:\phalcon-tools といったローカル HDD の任意のパスに展開してください。以降のステップでそのパスが必要になります。それから、「phalcon.bat」を選択し、右クリックメニューから「編集」を選び、編集します。 ![]() Phalcon 開発者ツールをインストールした場所にパスを変更します。 (ここでは PTOOLSPATH=C:phalcon-toolsに設定): ![]() 変更したら保存します。 スクリプトも PHP で書かれているので、あなたのマシンにも PHP のインストールが必要になります。PHP の実行ファイルはインストール方法に依存して様々な場所に配置されます。php.exe ファイルを検索してそのパスをコピーしてください。最新の WAMP スタックを使っている場合は、PHP は C:\wampbin\php\php5.3.10\php.exe にあります。 Windows のスタートメニューにて「コンピュータ」を右クリック、「プロパティ」を選びます。 ![]() 詳細設定のタブから「環境変数」を押します。 ![]() 下側の「システム環境変数」セクションから、変数「Path」を見つけて編集します。 ![]() この手順は気をつけてください! Path 変数の長い文字列の最後に、php.exe へのパスと開発者ツールをインストールしたパスを追加します。変数内の文字列で異なるパスを分けるには、「;(セミコロン)」を使います。 ![]() 変更後「OK」を押し、ダイアログボックスを閉じましょう。スタートメニューから「ファイル名を指定して実行」を選びます。スタートメニューから見つけられない場合は、「ウィンドウズキー」と「R」を押してください。 ![]() Windows のコマンドプロンプトを開くため、 ![]() コマンド ![]() おめでとうございます!これで Phalcon 開発者ツールがインストールされました! 下記のステップは OS X / macOS に Phalcon 開発者ツールをインストールするための手順を示すものです。 Download セクションで、開発者ツールを同梱したクロスプラットフォームのパッケージがダウンロードできます。また、Github から clone でもできます。 ターミナルアプリケーションを開き: ![]() コピー & ペーストでターミナルに下記のコマンドを貼り付けます: git clone git://github.com/phalcon/phalcon-devtools.git
ツールを clone したフォルダに移動し、”. ./phalcon.sh” を実行します(コマンドの最初のドットを忘れないでください)。: cd phalcon-devtools/
. ./phalcon.sh
ターミナルで次のコマンドを入力し、スクリプト phalcon.php へのシンボリックリンクを作成します。: ln -s ~/phalcon-tools/phalcon.php ~/phalcon-tools/phalcon
chmod +x ~/phalcon-tools/phalcon
“phalcon” とコマンドを入力すると下記のようになります。: ![]() おめでとうございます!これで Phalcon 開発者ツールがインストールされました! 下記のステップは Linux に Phalcon 開発者ツールをインストールするための手順を示すものです。 Download セクションで、開発者ツールを同梱したクロスプラットフォームのパッケージがダウンロードできます。また、Github から clone でもできます。 ターミナルを開き、下記のコマンドを入力します: git clone git://github.com/phalcon/phalcon-devtools.git
![]() ツールを clone したフォルダに移動し、”. ./phalcon.sh” を実行します(コマンドの最初のドットを忘れないでください)。: cd phalcon-devtools/
. ./phalcon.sh
![]() スクリプト phalcon.php へのシンボリックリンクを作成します: ln -s ~/phalcon-devtools/phalcon.php /usr/bin/phalcon
chmod ugo+x /usr/bin/phalcon
おめでとうございます!これで Phalcon 開発者ツールがインストールされました! 利用可能なコマンドの取得¶You can get a list of available commands in Phalcon tools by typing: $ 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)
プロジェクトスケルトンの生成¶You can use Phalcon tools to generate pre-defined project skeletons for your applications with Phalcon framework. By default the project skeleton generator will use mod_rewrite for Apache. Type the following command on your web server document root: $ pwd
/Applications/MAMP/htdocs
$ phalcon create-project store
The above recommended project structure was generated: ![]() You could add the parameter –help to get help on the usage of a certain script: $ 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]
--directory=s Base path on which project will be created [optional]
--type=s Type of the application to be generated (cli, micro, simple, modules)
--template-path=s Specify a template path [optional]
--use-config-ini Use a ini file as configuration file [optional]
--trace Shows the trace of the framework in case of exception. [optional]
--help Shows this help
Accessing the project from the web server will show you: ![]() コントローラの生成¶The command “create-controller” generates controller skeleton structures. It’s important to invoke this command inside a directory that already has a Phalcon project. $ phalcon create-controller --name test
The following code is generated by the script: <?php
use Phalcon\Mvc\Controller;
class TestController extends Controller
{
public function indexAction()
{
}
}
データベース設定の準備¶When a project is generated using developer tools. A configuration file can be found in app/config/config.ini To generate models or scaffold, you will need to change the settings used to connect to your database. Change the database section in your config.ini file: [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/"
モデルの生成¶There are several ways to create models. You can create all models from the default database connection or some selectively. Models can have public attributes for the field representations or setters/getters can be used.
The simplest way to generate a model is: $ phalcon model products
$ phalcon model --name tablename
All table fields are declared public for direct access. <?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;
}
By adding the –get-set you can generate the fields with protected variables and public setter/getter methods. Those methods can help in business logic implementation within the setter/getter methods. <?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;
/**
* Method to set the value of field id
*
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* Method to set the value of field typesId
*
* @param integer $typesId
*/
public function setTypesId($typesId)
{
$this->typesId = $typesId;
}
// ...
/**
* Returns the value of field status
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
}
A nice feature of the model generator is that it keeps changes made by the developer between code generations. This allows the addition or removal of fields and properties, without worrying about losing changes made to the model itself. The following screencast shows you how it works: CRUDのScaffolding¶Scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job. Once the code is generated, it will have to be customized to meet your needs. Many developers avoid scaffolding entirely, opting to write all or most of their source code from scratch. The generated code can serve as a guide to better understand of how the framework works or develop prototypes. The code below shows a scaffold based on the table “products”: $ phalcon scaffold --table-name products
The scaffold generator will build several files in your application, along with some folders. Here’s a quick overview of what will be generated:
When browsing the recently generated controller, you will see a search form and a link to create a new Product: ![]() The “create page” allows you to create products applying validations on the Products model. Phalcon will automatically validate not null fields producing warnings if any of them is required. ![]() After performing a search, a pager component is available to show paged results. Use the “Edit” or “Delete” links in front of each result to perform such actions. ![]() ツールへのWEBインターフェース¶Also, if you prefer, it’s possible to use Phalcon Developer Tools from a web interface. Check out the following screencast to figure out how it works: ツールとPhpStorm IDEとの統合¶The screencast below shows how to integrate developer tools with the PhpStorm IDE. The configuration steps could be easily adapted to other IDEs for PHP. まとめ¶Phalcon Developer Tools provides an easy way to generate code for your application, reducing development time and potential coding errors. チュートリアル¶チュートリアル 1: 例題で学習しよう¶この最初のチュートリアルでは、簡単な登録フォームを使用したアプリケーションをゼロから作成する手順を見ていきます。 また、フレームワークの動作の基本的な側面を説明していきます。もしあなたが Phalcon のコード自動生成ツールに興味があるのでしたら、次のドキュメントを参照ください。 developer tools. このガイドを使用する最良の方法は、順番にそれぞれのステップに従うことです。完全なコードは、ここ から取得することができます。 ファイル構造¶Phalcon はアプリケーション開発において特定のファイル構造を強制しません。Phalcon は疎結合になっているため、あなたのやりやすいファイル構造でアプリケーションを実装することができます。 このチュートリアルの出発点として、次のような構造にしてみましょう。 tutorial/
app/
controllers/
models/
views/
public/
css/
img/
js/
Phalcon に関連した “library” ディレクトリを必要としないことに注意してください。フレームワークはメモリ内で利用可能となっています。 続ける前に、必ず Phalcon のインストール(installed Phalcon)と、Nginx、Apache、Cherokee のいずれかの設定をしておいてください。 Bootstrap¶あなたが最初に作成する必要のあるファイルは bootstrap ファイルです。このファイルはとても重要であり、アプリケーションのベースとなり、すべての側面をコントロールすることを可能にします。このファイルでは、コンポーネントの初期化だけでなく、アプリケーションの振る舞いを実装することができます。 結局のところ、下記の3つを行う事になります。
オートローダの設定¶bootstrap の最初の部分では、オートローダを登録しています。これは、アプリケーション内のコントローラやモデルなどのクラスをロードするために使用されます。例えば、アプリケーションの柔軟性を増加させる、コントローラの1つまたは複数のディレクトリを登録することができます。この例では、Phalcon\Loader コンポーネントを使用しています。 これにより、様々な方法でクラスをロードすることができますが、この例ではあらかじめ定義されたディレクトリに基づいてクラスを検索することにします。 <?php
use Phalcon\Loader;
// ...
$loader = new Loader();
$loader->registerDirs(
[
"../app/controllers/",
"../app/models/",
]
);
$loader->register();
依存性の管理¶Phalcon で開発する際に、理解するべき非常に重要なコンセプトは DI コンテナ(dependency injection container)です。複雑そうに聞こえますが、実はシンプルで実用的なものです。 サービスコンテナは、アプリケーションが機能するために使用するサービスをグローバルに保存する入れ物です。フレームワークはコンポーネントを必要とするたびに、サービスに決められた名称でコンテナに問い合わせます。Phalcon はとても疎結合なフレームワークです。Phalcon\Di は接着剤として機能し、透過的にさまざまなコンポーネントを統合し、協調して動作できるように機能します。 <?php
use Phalcon\Di\FactoryDefault;
// ...
// DIコンテナを作る
$di = new FactoryDefault();
Phalcon\Di\FactoryDefault は Phalcon\Di の亜種です。処理をシンプルにするため、Phalcon に付属しているコンポーネントのほとんどが登録されています。 従って、それらをひとつひとつ登録するべきではありません。あとで生成するサービスを変更しても問題ありません。 次のパートでは、フレームワークが view ファイルを探すディレクトリを示す “view” サービスを登録します。 view ファイルはクラスでないため、オートローダで補完されません。 サービスを登録する方法はいくつかありますが、このチュートリアルでは無名関数 ( anonymous function ) を使用します。 <?php
use Phalcon\Mvc\View;
// ...
// ビューのコンポーネントの組み立て
$di->set(
"view",
function () {
$view = new View();
$view->setViewsDir("../app/views/");
return $view;
}
);
次に、Phalcon により生成されるすべての URI に “tutorial” が含まれるように、base 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;
}
);
アプリケーションリクエストの対処¶このファイルの最後のパートで、Phalcon\Mvc\Application を見つけるでしょう。この目的は、リクエスト環境を初期化し、リクエストのルートを決め、発見したアクションを起動することであり、処理が完了した際にレスポンスを集約し、返却することです。 <?php
use Phalcon\Mvc\Application;
// ...
$application = new Application($di);
$response = $application->handle();
$response->send();
全てまとめると¶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();
}
ご覧のように、bootstrap ファイルはとても短く、追加のファイルを読み込む必要はありません。柔軟な MVC アプリケーションの設定が、30行足らずのコードで行えるのです。 コントローラの作成¶デフォルトでは、Phalcon は “Index” という名称のコントローラを探します。これは、リクエスト内でコントローラまたはアクションが省略されている場合の出発点となります。index コントローラ (app/controllers/IndexController.php) は、次のようになります。 <?php
use Phalcon\Mvc\Controller;
class IndexController extends Controller
{
public function indexAction()
{
echo "<h1>Hello!</h1>";
}
}
コントローラクラスには、”Controller” という接尾語をつける必要があり、コントローラアクションには、”Action” という接尾語をつける必要があります。あなたがブラウザからアプリケーションにアクセスしたならば、次のように見えるでしょう。 ![]() おめでとうございます。あなたは Phalcon で飛び立つことができました! View へのアウトプットの送信¶コントローラーから画面に出力を送信することは時に必要ですが、しかし MVC 主義者のコミュニティが証明するように、望ましくはありません。レスポンスを返せるために画面上に出力するデータ全てを view に渡す必要があります。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 スタティックコンポーネントが自動的に生成されます。View の使い方について詳しくは こちら を参照ください。 サインアップフォームのデザイン¶今度は、index.phtml を編集して、「signup」という名前の新しいコントローラーへのリンクを追加してみましょう。目標は、ユーザーがアプリケーションにログインできるようにすることです。 <?php
echo "<h1>Hello!</h1>";
echo PHP_EOL;
echo PHP_EOL;
echo $this->tag->linkTo(
"signup",
"Sign Up Here!"
);
生成された HTML コードは、新しいコントローラーへリンクをしているアンカー(“a”)タグです。 <h1>Hello!</h1>
<a href="/tutorial/signup">Sign Up Here!</a>
タグを生成するには、Phalcon\Tag を使用します。このユーティリティクラスによって、フレームワークの規約に従ったHTMLタグを生成することができます。HTML生成機能の詳細については、 ここ を参照してください。 ![]() 以下が、Signup コントローラーです(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>
ブラウザーでフォームを確認すると、以下のように表示されるはずです。 ![]() Phalcon\Tag はまた、フォーム要素を組み立てるのに役に立つ方法を提供します。
送信ボタンをクリックすると、「signup」コントローラーの「register」アクションが見つからない、という例外が投げられることに気づくはずです。 public/index.php が以下の例外を投げています:
以下のようにメソッドを実装すれば、例外が無くなります: <?php
use Phalcon\Mvc\Controller;
class SignupController extends Controller
{
public function indexAction()
{
}
public function registerAction()
{
}
}
送信ボタンをもう一度クリックすると、空のページが表示されるでしょう。ユーザーが入力した名前とEメールアドレスは、データベースに保存すべきです。MVC のガイドラインによると、データベースとの連携はモデルで行わなければなりません。そうすることで、きれいなオブジェクト指向のコードを保つことができます。 モデルの作成¶Phalcon は、PHP に初めて全て C 言語で書かれた ORM を提供します。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;
}
データベース接続の設定¶データベース接続を使用できるようにし、モデルからデータにアクセスできるようにするため、bootstrap の途中でデータベース接続を明確にする必要があります。データベース接続は、アプリケーションが所有し、他のコンポーネントで利用可能なサービスです: <?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",
]
);
}
);
正しいデータベースのパラメーターが設定されれば、モデルが使用可能になり、アプリケーションの他の部分とやりとりできるようになります。 モデルを使用したデータの保存¶次のステップでは、フォームからデータを受け取って、テーブルに保存します。 <?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();
}
}
まず、Users クラスをインスタンス化します。これはユーザーのレコードに対応しています。クラスの public プロパティは、users テーブルのレコードのフィールドをマッピングしています。適切な値を新しいレコードに設定し、 ORMは自動的に入力値をエスケープし、SQLインジェクションを防ぎます。リクエストを:code:`save()`メソッドに渡すだけでよいのです。 Not Null (必須パラメーター) 制約の課されたフィールドには、自動的にバリデーションが追加されます。登録フォームに何も入力しなければ、以下のように表示されます: ![]() まとめ¶この簡単なチュートリアルで分かるように、Phalcon でアプリケーションを作り始めることは簡単です。Phalcon が Web サーバの拡張で動作するという事実は、開発のしやすさ、または機能の使いやすさを阻害する訳ではありません。マニュアルを読み進める事で、Phalcon が提供する様々な機能を知ることができるでしょう! チュートリアル 2: Introducing INVO¶この第2のチュートリアルでは、より完全なアプリケーションを例にして説明し、Phalconを使用した開発について理解を深めます。INVOは、私達が制作したサンプルアプリケーションの1つです。INVOは小さなWebサイトで、ユーザーは送り状(invoice)を生成したり、顧客や製品を管理したりといったタスクを行うことができます。コードは Github からクローンすることができます。 また、INVOのクライアントサイドは Bootstrap を使用して作られています。アプリケーションが送り状を生成しなくても、フレームワークの働きを理解するサンプルにはなります。 プロジェクト構造¶ブラウザで http://localhost/invo にアクセスしてアプリケーションを開くと、以下のように表示されるでしょう: invo/
app/
config/
controllers/
forms/
library/
logs/
models/
plugins/
views/
cache/
volt/
docs/
public/
css/
fonts/
js/
schemas/
ご存知のように、Phalconはアプリケーション開発に際して特定の構造を強制しません。このプロジェクトはシンプルなMVC構造を持ち、publicディレクトリをドキュメントルートとします。 ブラウザで http://localhost/invo にアクセスしてアプリケーションを開くと、以下のように表示されるでしょう: ![]() アプリケーションは2つの部分に分かれています。フロントエンドは公開されている部分で、訪問者はINVOの概要を知ったり、連絡を求めたりできます。もう一つはバックエンドで、管理用の領域です。登録されたユーザーが、製品や顧客を管理できます。 ルーティング¶INVOはRouterコンポーネントに組み込みの標準のルートを使用します。これらのルートは、 /:controller/:action/:params というパターンにマッチします。これは、URIの最初の部分がコントローラー、2番めの部分がアクション、残りがパラメーターになる、ということです。 /session/register というルートでは、SessionController コントローラの registerAction アクションが実行されます。 設定 (Configuration)¶INVOには、アプリケーションの一般的なパラメーターをセットする設定ファイルがあります。このファイルはブートストラップ (public/index.php) の最初の数行で読み込まれています: <?php
use Phalcon\Config\Adapter\Ini as ConfigIni;
// ...
// 設定の読み込み
$config = new ConfigIni(
APP_PATH . "app/config/config.ini"
);
Phalcon\Config を使うと設定ファイルをオブジェクト指向のやり方で操作できます。 設定ファイルは以下の設定を含んでいます: [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には、定義済みの慣習的な設定は全くありません。セクション名を付けておくと、オプションを適切に構成する助けになります。このファイルには3つのセクションが含まれ、後で使用されます。 オートローダ¶ブートストラップファイル (public/index.php) の2番めのパートは、オートローダーです。 <?php
/**
* Auto-loader configuration
*/
require APP_PATH . "app/config/loader.php";
オートローダーにディレクトリを登録すると、アプリケーションは、必要になったクラスを登録されたディレクトリ内で探します。 <?php
$loader = new Phalcon\Loader();
// 設定ファイルに書かれていたディレクトリを登録する
$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ディレクトリだけは、登録しません。viewsDirにはHTMLファイルとPHPファイルが含まれますが、クラスは含まれていないからです。 また、APP_PATHという定数を使っていることに注意してください。この定数はブートストラップファイル(public/index.php)で定義されているもので、プロジェクトのルートパスを参照することができます。 <?php
// ...
define(
"APP_PATH",
realpath("..") . "/"
);
サービスの登録¶ブートストラップで必要とされる他のファイルは(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;
}
);
後で、我々はこのファイルについてより深く論じます。 リクエストの処理¶ファイルの最後まで飛ばすと、リクエストは最終的に Phalcon\Mvc\Application に処理されています。このクラスは、アプリケーションに必要な全ての初期化と処理の実行を行います: <?php
use Phalcon\Mvc\Application;
// ...
$application = new Application($di);
$response = $application->handle();
$response->send();
依存性の注入 (Dependency Injection)¶上記コード例の1行目を見てください。 Application クラスのコンストラクタは、 コンテナにサービスを登録するには、様々な方法があります。INVOでは、ほとんどのサービスは無名関数を使って登録されています。このおかげで、オブジェクトは必要になるまでインスタンス化されないので、アプリケーションに必要なリソースが節約できます。 たとえば、以下の抜粋では、sessionサービスが登録されています。無名関数は、アプリケーションがsessionのデータへのアクセスを要求した時に初めて呼ばれます: <?php
use Phalcon\Session\Adapter\Files as Session;
// ...
// コンポーネントがsessionサービスを最初に要求した時に、セッションを開始する
$di->set(
"session",
function () {
$session = new Session();
$session->start();
return $session;
}
);
これで、アダプタを変更して、初期化処理を追加する等を自由に行えるようになりました。サービスは “session” という名前で登録されていることに注意してください。これは、フレームワークがサービスコンテナ内の有効なサービスを見分けるための慣習です。 リクエストは多数のサービスを利用する可能性があり、それらを1つずつ登録するのは面倒な作業です。そのため、Phalconは Phalcon\Di\FactoryDefault という Phalcon\Di の別バージョンを用意しています。これには、フルスタックフレームワークのための全てのサービスを登録します。 <?php
use Phalcon\Di\FactoryDefault;
// ...
// FactoryDefault は、フルスタックフレームワークを
// 提供するために必要なサービスを自動的に登録する
$di = new FactoryDefault();
FactoryDefault はフレームワークが標準的に提供しているコンポーネントサービスの大部分を登録します。もし、サービス定義のオーバーライドが必要な場合、”session” を上で定義したのと同じように同じ名前で再度定義してください。以上が、 次の章では、INVOに認証と承認を実装する方法を見ていきます。 Tutorial 3: Securing INVO¶In this chapter, we continue explaining how INVO is structured, we’ll talk about the implementation of authentication, authorization using events and plugins and an access control list (ACL) managed by Phalcon. アプリケーションへのログイン¶ログイン機能によって、バックエンドのコントローラーに取り組むことができるようになります。バックエンドとフロントエンドのコントローラーの分割は、論理上のものです。全てのコントローラーは、同じディレクトリ (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() }}
Instead of using raw PHP as the previous tutorial, we started to use Volt. This is a built-in template engine inspired in Jinja providing a simpler and friendly syntax to create templates. It will not take too long before you become familiar with Volt.
<?php
class SessionController extends ControllerBase
{
// ...
private function _registerSession($user)
{
$this->session->set(
"auth",
[
"id" => $user->id,
"name" => $user->name,
]
);
}
/**
* This action authenticate and logs a user into the application
*/
public function startAction()
{
if ($this->request->isPost()) {
// POSTで送信された変数を受け取る
$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” を使ってください。 コントローラー内で これらのサービスは共有されているため、これらのオブジェクトをどこから呼び出しても、常に同じインスタンスにアクセスすることになります。 例えば、ここで “session” サービスを呼び出して、ユーザーを識別する情報を “auth” という変数に保存しています: <?php
$this->session->set(
"auth",
[
"id" => $user->id,
"name" => $user->name,
]
);
Another important aspect of this section is how the user is validated as a valid one, first we validate whether the request has been made using method POST: <?php
if ($this->request->isPost()) {
Then, we receive the parameters from the form: <?php
$email = $this->request->getPost("email");
$password = $this->request->getPost("password");
Now, we have to check if there is one user with the same username or email and password: <?php
$user = Users::findFirst(
[
"(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
"bind" => [
"email" => $email,
"password" => sha1($password),
]
]
);
Note, the use of ‘bound parameters’, placeholders :email: and :password: are placed where values should be, then the values are ‘bound’ using the parameter ‘bind’. This safely replaces the values for those columns without having the risk of a SQL injection. If the user is valid we register it in session and forwards him/her to the dashboard: <?php
if ($user !== false) {
$this->_registerSession($user);
$this->flash->success(
"Welcome " . $user->name
);
return $this->dispatcher->forward(
[
"controller" => "invoices",
"action" => "index",
]
);
}
If the user does not exist we forward the user back again to action where the form is displayed: <?php
return $this->dispatcher->forward(
[
"controller" => "session",
"action" => "index",
]
);
バックエンドのセキュリティ保護¶バックエンドは登録されたユーザーだけがアクセスできるプライベートな領域です。したがって、登録されたユーザーだけがそれらのコントローラーにアクセスできるようチェックする必要があります。たとえば、ログインせずに products コントローラー (プライベート領域) にアクセスしようとすると、以下のように表示されるはずです: ![]() コントローラー・アクションにアクセスしようとしたときにはいつでも、アプリケーションは現在のロール (セッションに含まれる) が、アクセス権を持っているか確認します。アクセス権がない場合は、上のようなメッセージを表示し、インデックスページに遷移させます。 次に、アプリケーションがこの動きをどのように実現しているか見ていきましょう。最初に知るべきは、Dispatcher コンポーネントです。これは、 Routing コンポーネントによって発見されたルートの情報を受け取ります。次に、適切なコントローラーを読み込んで、対応するアクションのメソッドを実行します。 通常、フレームワークはディスパッチャを自動的に作成します。今回は、要求されたアクションを実行する前に、認証を行い、ユーザーがアクセスできるか否かチェックする必要があります。これを実現するため、ブートストラップの中に関数を用意して、ディスパッチャを置き換えています: <?php
use Phalcon\Mvc\Dispatcher;
// ...
/**
* MVC dispatcher
*/
$di->set(
"dispatcher",
function () {
// ...
$dispatcher = new Dispatcher();
return $dispatcher;
}
);
これで、アプリケーションで使用されるディスパッチャを完全に制御できるようになりました。フレーワークの多くのコンポーネントはイベントを発火するので、内部の処理の流れを変更することができます。DIコンポーネントが接着剤として機能し、 EventsManager がコンポーネントが生み出すイベントをインターセプトし、イベントをリスナーに通知します。 イベント管理¶EventsManager によって、特定のタイプのイベントにリスナーを割り当てることができます。今、私達が取り組んでいるイベントのタイプは “dispatch” です。以下のコードは、ディスパッチャによって生成される全てのイベントをフィルタリングしています: <?php
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an events manager
$eventsManager = new EventsManager();
// Securityプラグインを使用して、ディスパッチャが生成するイベントを監視する
$eventsManager->attach(
"dispatch:beforeExecuteRoute",
new SecurityPlugin()
);
// Handle exceptions and not-found exceptions using NotFoundPlugin
$eventsManager->attach(
"dispatch:beforeException",
new NotFoundPlugin()
);
$dispatcher = new Dispatcher();
// イベントマネージャーをディスパッチャに束縛する
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
When an event called “beforeExecuteRoute” is triggered the following plugin will be notified: <?php
/**
* Check if the user is allowed to access certain action using the SecurityPlugin
*/
$eventsManager->attach(
"dispatch:beforeExecuteRoute",
new SecurityPlugin()
);
When a “beforeException” is triggered then other plugin is notified: <?php
/**
* Handle exceptions and not-found exceptions using NotFoundPlugin
*/
$eventsManager->attach(
"dispatch:beforeException",
new NotFoundPlugin()
);
Securityプラグインは (app/plugins/SecurityPlugin.php) にあるクラスです。このクラスは “beforeExecuteRoute” メソッドを実装しています。これは、ディスパッチャーが生成するイベントの1つと同じ名前です: <?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)
{
// ...
}
}
フックイベントは常に2つの引数を取ります。第1引数はイベントが生成されたコンテキストの情報( 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)
{
// ロールを定義するため、セッションに "auth" 変数があるかチェックする
$auth = $this->session->get("auth");
if (!$auth) {
$role = "Guests";
} else {
$role = "Users";
}
// ディスパッチャからアクティブなコントローラー名とアクション名を取得する
$controller = $dispatcher->getControllerName();
$action = $dispatcher->getActionName();
// ACLリストを取得
$acl = $this->getAcl();
// ロールがコントローラー (又はリソース) にアクセス可能かチェックする
$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リストの提供¶上の例では、 <?php
use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Adapter\Memory as AclList;
// ACLオブジェクトを作る
$acl = new AclList();
// デフォルトの挙動はDENY(拒否)
$acl->setDefaultAction(
Acl::DENY
);
// 2つのロールを登録する
// ユーザーは登録済みユーザー、ゲストは未登録ユーザー
$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
// 公開エリアのアクセス権をユーザーとゲストの双方に与える
foreach ($roles as $role) {
foreach ($publicResources as $resource => $actions) {
$acl->allow(
$role->getName(),
$resource,
"*"
);
}
}
// ユーザーにだけ、プライベートエリアへのアクセス権を与える
foreach ($privateResources as $resource => $actions) {
foreach ($actions as $action) {
$acl->allow(
"Users",
$resource,
$action
);
}
}
万歳! これで、ACLは終わりです。 In next chapter, we will see how a CRUD is implemented in Phalcon and how you can customize it. Tutorial 4: CRUDを使用した作業¶Backends usually provide forms to allow users to manipulate data. Continuing the explanation of INVO, we now address the creation of CRUDs, a very common task that Phalcon will facilitate you using forms, validations, paginators and more. Most options that manipulate data in INVO (companies, products and types of products) were developed using a basic and common CRUD (Create, Read, Update and Delete). Each CRUD contains the following files: invo/
app/
controllers/
ProductsController.php
models/
Products.php
forms/
ProductsForm.php
views/
products/
edit.volt
index.volt
new.volt
search.volt
Each controller has the following actions: <?php
class ProductsController extends ControllerBase
{
/**
* The start action, it shows the "search" view
*/
public function indexAction()
{
// ...
}
/**
* Execute the "search" based on the criteria sent from the "index"
* Returning a paginator for the results
*/
public function searchAction()
{
// ...
}
/**
* Shows the view to create a "new" product
*/
public function newAction()
{
// ...
}
/**
* Shows the view to "edit" an existing product
*/
public function editAction()
{
// ...
}
/**
* Creates a product based on the data entered in the "new" action
*/
public function createAction()
{
// ...
}
/**
* Updates a product based on the data entered in the "edit" action
*/
public function saveAction()
{
// ...
}
/**
* Deletes an existing product
*/
public function deleteAction($id)
{
// ...
}
}
検索フォーム¶Every CRUD starts with a search form. This form shows each field that the table has (products), allowing the user to create a search criteria for any field. The “products” table has a relationship with the table “products_types”. In this case, we previously queried the records in this table in order to facilitate the search by that field: <?php
/**
* The start action, it shows the "search" view
*/
public function indexAction()
{
$this->persistent->searchParams = null;
$this->view->form = new ProductsForm();
}
An instance of the ProductsForm form (app/forms/ProductsForm.php) is passed to the view. This form defines the fields that are visible to the user: <?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
{
/**
* Initialize the products 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);
}
}
The form is declared using an object-oriented scheme based on the elements provided by the forms component. Every element follows almost the same structure: <?php
// Create the element
$name = new Text("name");
// Set its label
$name->setLabel("Name");
// Before validating the element apply these filters
$name->setFilters(
[
"striptags",
"string",
]
);
// Apply this validators
$name->addValidators(
[
new PresenceOf(
[
"message" => "Name is required",
]
)
]
);
// Add the element to the form
$this->add($name);
Other elements are also used in this form: <?php
// Add a hidden input to the form
$this->add(
new Hidden("id")
);
// ...
$productTypes = ProductTypes::find();
// Add a HTML Select (list) to the form
// and fill it with data from "product_types"
$type = new Select(
"profilesId",
$productTypes,
[
"using" => [
"id",
"name",
],
"useEmpty" => true,
"emptyText" => "...",
"emptyValue" => "",
]
);
Note that {{ 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() }}
This produces the following 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>
When the form is submitted, the “search” action is executed in the controller performing the search based on the data entered by the user. 検索の実行¶The “search” action has two behaviors. When accessed via POST, it performs a search based on the data sent from the form but when accessed via GET it moves the current page in the paginator. To differentiate HTTP methods, we check it using the Request component: <?php
/**
* Execute the "search" based on the criteria sent from the "index"
* Returning a paginator for the results
*/
public function searchAction()
{
if ($this->request->isPost()) {
// Create the query conditions
} else {
// Paginate using the existing conditions
}
// ...
}
With the help of Phalcon\Mvc\Model\Criteria, we can create the search conditions intelligently based on the data types and values sent from the form: <?php
$query = Criteria::fromInput(
$this->di,
"Products",
$this->request->getPost()
);
This method verifies which values are different from “” (empty string) and null and takes them into account to create the search criteria:
Additionally, “Criteria” ignores all the Now, we store the produced parameters in the controller’s session bag: <?php
$this->persistent->searchParams = $query->getParams();
A session bag, is a special attribute in a controller that persists between requests using the session service. When accessed, this attribute injects a Phalcon\Session\Bag instance that is independent in each controller. Then, based on the built params we perform the query: <?php
$products = Products::find($parameters);
if (count($products) === 0) {
$this->flash->notice(
"The search did not found any products"
);
return $this->dispatcher->forward(
[
"controller" => "products",
"action" => "index",
]
);
}
If the search doesn’t return any product, we forward the user to the index action again. Let’s pretend the search returned results, then we create a paginator to navigate easily through them: <?php
use Phalcon\Paginator\Adapter\Model as Paginator;
// ...
$paginator = new Paginator(
[
"data" => $products, // Data to paginate
"limit" => 5, // Rows per page
"page" => $numberPage, // Active page
]
);
// Get active page in the paginator
$page = $paginator->getPaginate();
Finally we pass the returned page to view: <?php
$this->view->page = $page;
In the view (app/views/products/search.volt), we traverse the results corresponding to the current page, showing every row in the current page to the user: {% for product in page.items %}
{% if loop.first %}
<table>
<thead>
<tr>
<th>Id</th>
<th>Product Type</th>
<th>Name</th>
<th>Price</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{% endif %}
<tr>
<td>
{{ product.id }}
</td>
<td>
{{ product.getProductTypes().name }}
</td>
<td>
{{ product.name }}
</td>
<td>
{{ "%.2f"|format(product.price) }}
</td>
<td>
{{ product.getActiveDetail() }}
</td>
<td width="7%">
{{ link_to("products/edit/" ~ product.id, "Edit") }}
</td>
<td width="7%">
{{ link_to("products/delete/" ~ product.id, "Delete") }}
</td>
</tr>
{% if loop.last %}
</tbody>
<tbody>
<tr>
<td colspan="7">
<div>
{{ link_to("products/search", "First") }}
{{ link_to("products/search?page=" ~ page.before, "Previous") }}
{{ link_to("products/search?page=" ~ page.next, "Next") }}
{{ link_to("products/search?page=" ~ page.last, "Last") }}
<span class="help-inline">{{ page.current }} of {{ page.total_pages }}</span>
</div>
</td>
</tr>
</tbody>
</table>
{% endif %}
{% else %}
No products are recorded
{% endfor %}
There are many things in the above example that worth detailing. First of all, active items in the current page are traversed using a Volt’s ‘for’. Volt provides a simpler syntax for a PHP ‘foreach’. {% for product in page.items %}
Which in PHP is the same as: <?php foreach ($page->items as $product) { ?>
The whole ‘for’ block provides the following: {% for product in page.items %}
{% if loop.first %}
Executed before the first product in the loop
{% endif %}
Executed for every product of page.items
{% if loop.last %}
Executed after the last product is loop
{% endif %}
{% else %}
Executed if page.items does not have any products
{% endfor %}
Now you can go back to the view and find out what every block is doing. Every field in “product” is printed accordingly: <tr>
<td>
{{ product.id }}
</td>
<td>
{{ product.productTypes.name }}
</td>
<td>
{{ product.name }}
</td>
<td>
{{ "%.2f"|format(product.price) }}
</td>
<td>
{{ product.getActiveDetail() }}
</td>
<td width="7%">
{{ link_to("products/edit/" ~ product.id, "Edit") }}
</td>
<td width="7%">
{{ link_to("products/delete/" ~ product.id, "Delete") }}
</td>
</tr>
As we seen before using <?php
use Phalcon\Mvc\Model;
/**
* Products
*/
class Products extends Model
{
// ...
/**
* Products initializer
*/
public function initialize()
{
$this->belongsTo(
"product_types_id",
"ProductTypes",
"id",
[
"reusable" => true,
]
);
}
// ...
}
A model can have a method called <?php
$this->belongsTo(
"product_types_id",
"ProductTypes",
"id",
[
"reusable" => true,
]
);
Which means, the local attribute “product_types_id” in “Products” has an one-to-many relation to the “ProductTypes” model in its attribute “id”. By defining this relationship we can access the name of the product type by using: <td>{{ product.productTypes.name }}</td>
The field “price” is printed by its formatted using a Volt filter: <td>{{ "%.2f"|format(product.price) }}</td>
In plain PHP, this would be: <?php echo sprintf("%.2f", $product->price) ?>
Printing whether the product is active or not uses a helper implemented in the model: <td>{{ product.getActiveDetail() }}</td>
This method is defined in the model. レコードの登録と更新¶Now let’s see how the CRUD creates and updates records. From the “new” and “edit” views, the data entered by the user is sent to the “create” and “save” actions that perform actions of “creating” and “updating” products, respectively. In the creation case, we recover the data submitted and assign them to a new “Products” instance: <?php
/**
* Creates a product based on the data entered in the "new" action
*/
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");
// ...
}
Remember the filters we defined in the Products form? Data is filtered before being assigned to the object <?php
// ...
$name = new Text("name");
$name->setLabel("Name");
// Filters for name
$name->setFilters(
[
"striptags",
"string",
]
);
// Validators for name
$name->addValidators(
[
new PresenceOf(
[
"message" => "Name is required",
]
)
]
);
$this->add($name);
When saving, we’ll know whether the data conforms to the business rules and validations implemented in the form ProductsForm form (app/forms/ProductsForm.php): <?php
// ...
$form = new ProductsForm();
$product = new Products();
// Validate the input
$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",
]
);
}
Finally, if the form does not return any validation message we can save the product instance: <?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",
]
);
Now, in the case of updating a product, we must first present the user with the data that is currently in the edited record: <?php
/**
* Edits a product based on its 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,
]
);
}
}
The data found is bound to the form by passing the model as first parameter. Thanks to this, the user can change any value and then sent it back to the database through to the “save” action: <?php
/**
* Updates a product based on the data entered in the "edit" action
*/
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",
]
);
}
We have seen how Phalcon lets you create forms and bind data from a database in a structured way. In next chapter, we will see how to add custom HTML elements like a menu. Tutorial 5: Customizing INVO¶To finish the detailed explanation of INVO we are going to explain how to customize INVO adding UI elements and changing the title according to the controller executed. ユーザーコンポーネント¶全ての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
// Register a user component
$di->set(
"elements",
function () {
return new Elements();
}
);
As controllers, plugins or components within a view, this component also has access to the services registered in the container and by just accessing an attribute with the same name as a previously registered service: <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>© Company 2015</p>
</footer>
</div>
The important part is: {{ elements.getMenu() }}
タイトルの動的な変更¶When you browse between one option and another will see that the title changes dynamically indicating where we are currently working. This is achieved in each controller initializer: <?php
class ProductsController extends ControllerBase
{
public function initialize()
{
// Set the document title
$this->tag->setTitle(
"Manage your product types"
);
parent::initialize();
}
// ...
}
Note, that the method <?php
use Phalcon\Mvc\Controller;
class ControllerBase extends Controller
{
protected function initialize()
{
// Prepend the application name to the title
$this->tag->prependTitle(
"INVO | "
);
}
// ...
}
Finally, the title is printed in the main view (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: ![]() 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 <?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の作成¶In this tutorial, we will explain how to create a simple application that provides a RESTful API using the different HTTP methods:
APIの定義¶The API consists of the following methods:
アプリケーションの作成¶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: When a defined route matches the requested URI then the application executes the corresponding handler. モデルの作成¶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);
データの取得¶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;
}
);
データの登録¶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;
}
);
データの更新¶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;
}
);
データの削除¶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;
}
);
アプリケーションのテスト¶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"}
サンプル一覧¶Following examples are full applications you can use to learn more about Phalcon and use them as base for your own websites/applications: コンポーネント¶依存性の注入とサービス・ロケーション¶
Phalcon\Di は 依存性の注入や サービスの場所を実装するコンポーネントで、自分自身もコンテナです。 Phalconが高度に分離されているため、Phalcon\Di はフレームワークのさまざまなコンポーネントを統合することが不可欠です。開発者は、依存性を注入し、アプリケーションで使用されるさまざまなクラスのグローバルインスタンスを管理するには、このコンポーネントを使用することができます。 基本的には、このコンポーネントは、`コントロールの反転`パターンを実装しています。 基本的には、このコンポーネントは Inversion of Control パターンを実装しています。これを適用すると、オブジェクトは、その依存関係をセッターあるいはコンストラクタによって受け取るのではなく、サービスの依存性の注入を要求します。コンポーネント内の依存関係を得るための方法は一つだけですので、これによって全体的な複雑さが軽減されます。 加えて、このパターンによってコードがテストしやすくなり、エラーへの耐性が向上します。 サービスのコンテナへの登録¶フレームワーク自身だけでなく、開発者も、サービスを登録することができます。コンポーネントAが動作するのにコンポーネントB(あるいはそのクラスのインスタンス)を必要とする場合、コンポーネントBの新しいインスタンスを作るのではなく、コンテナからコンポーネントBを取り出します。 このやり方には、大きな利点があります:
サービスの登録には複数の書き方があります: 簡単な登録¶As seen before, there are several ways to register services. These we call simple: This type expects the name of a valid class, returning an object of the specified class, if the class is not loaded it will be instantiated using an auto-loader. This type of definition does not allow to specify arguments for the class constructor or parameters: <?php
// Return new Phalcon\Http\Request();
$di->set(
"request",
"Phalcon\\Http\\Request"
);
This type expects an object. Due to the fact that object does not need to be resolved as it is already an object, one could say that it is not really a dependency injection, however it is useful if you want to force the returned dependency to always be the same object/value: <?php
use Phalcon\Http\Request;
// Return new Phalcon\Http\Request();
$di->set(
"request",
new Request()
);
This method offers greater freedom to build the dependency as desired, however, it is difficult to change some of the parameters externally without having to completely change the definition of dependency: <?php
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
$di->set(
"db",
function () {
return new PdoMysql(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "blog",
]
);
}
);
Some of the limitations can be overcome by passing additional variables to the closure’s environment: <?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",
]
);
// Using the $config variable in the current scope
$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 <?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,
]
);
}
);
複雑な登録¶If it is required to change the definition of a service without instantiating/resolving the service, then, we need to define the services using the array syntax. Define a service using an array definition can be a little more verbose: <?php
use Phalcon\Logger\Adapter\File as LoggerFile;
// Register a service 'logger' with a class name and its parameters
$di->set(
"logger",
[
"className" => "Phalcon\\Logger\\Adapter\\File",
"arguments" => [
[
"type" => "parameter",
"value" => "../apps/logs/error.log",
]
]
]
);
// Using an anonymous function
$di->set(
"logger",
function () {
return new LoggerFile("../apps/logs/error.log");
}
);
Both service registrations above produce the same result. The array definition however, allows for alteration of the service parameters if needed: <?php
// Change the service class name
$di->getService("logger")->setClassName("MyCustomLogger");
// Change the first parameter without instantiating the logger
$di->getService("logger")->setParameter(
0,
[
"type" => "parameter",
"value" => "../apps/logs/error.log",
]
);
In addition by using the array syntax you can use three types of dependency injection: This injection type passes the dependencies/arguments to the class constructor. Let’s pretend we have the following component: <?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;
}
}
The service can be registered this way: <?php
$di->set(
"response",
[
"className" => "Phalcon\\Http\\Response"
]
);
$di->set(
"someComponent",
[
"className" => "SomeApp\\SomeComponent",
"arguments" => [
[
"type" => "service",
"name" => "response",
],
[
"type" => "parameter",
"value" => true,
],
]
]
);
The service “response” (Phalcon\Http\Response) is resolved to be passed as the first argument of the constructor, while the second is a boolean value (true) that is passed as it is. Classes may have setters to inject optional dependencies, our previous class can be changed to accept the dependencies with setters: <?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;
}
}
A service with setter injection can be registered as follows: <?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,
]
]
]
]
]
);
A less common strategy is to inject dependencies or parameters directly into public attributes of the class: <?php
namespace SomeApp;
use Phalcon\Http\Response;
class SomeComponent
{
/**
* @var Response
*/
public $response;
public $someFlag;
}
A service with properties injection can be registered as follows: <?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,
],
]
]
]
);
Supported parameter types include the following:
Resolving a service whose definition is complex may be slightly slower than simple definitions seen previously. However, these provide a more robust approach to define and inject services. Mixing different types of definitions is allowed, everyone can decide what is the most appropriate way to register the services according to the application needs. Array Syntax¶配列の記法でサービスを登録することもできます: <?php
use Phalcon\Di;
use Phalcon\Http\Request;
// 依存性を注入するコンテナ(DIコンテナ)を作成する
$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’という名前のサービスを求めます。コンテナは要求されたサービスのインスタンスを返します。開発者は、結果として、必要とするコンポーネントを置き換えることができます。 (上記例で使用された) サービス登録方法には、それぞれに利点と欠点があります。どの方法を使うかは、必要に応じて、開発者が決定します。 文字列でのサービス登録は、シンプルですが、柔軟性に欠けます。配列でのサービス登録は、より柔軟ですが、コードが複雑になります。無名関数にはこの2つの中間的なバランスの良さがありますが、意外とメンテナンスが大変です。 Phalcon\Di は全てのサービスを遅延読み込みします。開発者がオブジェクトを直接初期化してコンテナに入れようとしない限り、コンテナに格納されるあらゆるオブジェクトは、(その登録方法がどのような方法であっても)遅延読み込みされ、要求されるまではインスタンス化されません。 サービスの解決¶Obtaining a service from the container is a matter of simply calling the “get” method. A new instance of the service will be returned: <?php $request = $di->get("request");
Or by calling through the magic method: <?php
$request = $di->getRequest();
Or using the array-access syntax: <?php
$request = $di["request"];
Arguments can be passed to the constructor by adding an array parameter to the method “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:
共有サービス¶Services can be registered as “shared” services this means that they always will act as singletons. Once the service is resolved for the first time the same instance of it is returned every time a consumer retrieve the service from the container: <?php
use Phalcon\Session\Adapter\Files as SessionFiles;
// Register the session service as "always shared"
$di->setShared(
"session",
function () {
$session = new SessionFiles();
$session->start();
return $session;
}
);
// Locates the service for the first time
$session = $di->get("session");
// Returns the first instantiated object
$session = $di->getSession();
An alternative way to register shared services is to pass “true” as third parameter of “set”: <?php
// Register the session service as "always shared"
$di->set(
"session",
function () {
// ...
},
true
);
If a service isn’t registered as shared and you want to be sure that a shared instance will be accessed every time the service is obtained from the DI, you can use the ‘getShared’ method: <?php
$request = $di->getShared("request");
個別のサービスの操作¶Once a service is registered in the service container, you can retrieve it to manipulate it individually: <?php
use Phalcon\Http\Request;
// Register the "request" service
$di->set("request", "Phalcon\\Http\\Request");
// Get the service
$requestService = $di->getService("request");
// Change its definition
$requestService->setDefinition(
function () {
return new Request();
}
);
// Change it to shared
$requestService->setShared(true);
// Resolve the service (return a Phalcon\Http\Request instance)
$request = $requestService->resolve();
Instantiating classes via the Service Container¶When you request a service to the service container, if it can’t find out a service with the same name it’ll try to load a class with the same name. With this behavior we can replace any class by another simply by registering a service with its name: <?php
// Register a controller as a service
$di->set(
"IndexController",
function () {
$component = new Component();
return $component;
},
true
);
// Register a controller as a service
$di->set(
"MyOtherComponent",
function () {
// Actually returns another component
$component = new AnotherComponent();
return $component;
}
);
// Create an instance via the service container
$myComponent = $di->get("MyOtherComponent");
You can take advantage of this, always instantiating your classes via the service container (even if they aren’t registered as services). The DI will fallback to a valid autoloader to finally load the class. By doing this, you can easily replace any class in the future by implementing a definition for it. Automatic Injecting of the DI itself¶If a class or component requires the DI itself to locate services, the DI can automatically inject itself to the instances it creates, to do this, you need to implement the Phalcon\Di\InjectionAwareInterface in your classes: <?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;
}
}
Then once the service is resolved, the <?php
// Register the service
$di->set("myClass", "MyClass");
// Resolve the service (NOTE: $myClass->setDi($di) is automatically called)
$myClass = $di->get("myClass");
Organizing services in files¶You can better organize your application by moving the service registration to individual files instead of doing everything in the application’s bootstrap: <?php
$di->set(
"router",
function () {
return include "../app/config/routes.php";
}
);
Then in the file (”../app/config/routes.php”) return the object resolved: <?php
$router = new MyRouter();
$router->post("/login");
return $router;
静的な方法でのDIへのアクセス¶If needed you can access the latest DI created in a static function in the following way: <?php
use Phalcon\Di;
class SomeComponent
{
public static function someMethod()
{
// Get the session service
$session = Di::getDefault()->getSession();
}
}
Factory Default DI¶Although the decoupled character of Phalcon offers us great freedom and flexibility, maybe we just simply want to use it as a full-stack framework. To achieve this, the framework provides a variant of Phalcon\Di called Phalcon\Di\FactoryDefault. This class automatically registers the appropriate services bundled with the framework to act as full-stack. <?php
use Phalcon\Di\FactoryDefault;
$di = new FactoryDefault();
サービス名の規約¶Although you can register services with the names you want, Phalcon has a several naming conventions that allow it to get the the correct (built-in) service when you need it.
独自のDIの実装¶The Phalcon\DiInterface interface must be implemented to create your own DI replacing the one provided by Phalcon or extend the current one. MVCアーキテクチャ¶Phalcon offers the object-oriented classes, necessary to implement the Model, View, Controller architecture (often referred to as MVC) in your application. This design pattern is widely used by other web frameworks and desktop applications. MVC benefits include:
If you decide to use MVC, every request to your application resources will be managed by the MVC architecture. Phalcon classes are written in C language, offering a high performance approach of this pattern in a PHP based application. モデル (Models)¶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. Learn more ビュー (Views)¶Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. Learn more コントローラ (Controllers)¶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. Learn more コントローラの使用¶Actions are methods on a controller that handle requests. By default all public methods on a controller map to actions and are accessible by a URL. Actions are responsible for interpreting the request and creating the response. Usually responses are in the form of a rendered view, but there are other ways to create responses as well. For instance, when you access a URL like this: http://localhost/blog/posts/show/2015/the-post-title Phalcon by default will decompose each part like this:
In this case, the PostsController will handle this request. There is no a special location to put controllers in an application, they could be loaded using autoloaders, so you’re free to organize your controllers as you need. Controllers must have the suffix “Controller” while actions the suffix “Action”. A sample of a controller is as follows: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction($year, $postTitle)
{
}
}
Additional URI parameters are defined as action parameters, so that they can be easily accessed using local variables. A controller can optionally extend Phalcon\Mvc\Controller. By doing this, the controller can have easy access to the application services. Parameters without a default value are handled as required. Setting optional values for parameters is done as usual in PHP: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction($year = 2015, $postTitle = "some default title")
{
}
}
Parameters are assigned in the same order as they were passed in the route. You can get an arbitrary parameter from its name in the following way: <?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¶The dispatch loop will be executed within the Dispatcher until there are no actions left to be executed. In the previous example only one
action was executed. Now we’ll see how the <?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",
]
);
}
}
If users don’t have permission to access a certain action then they will be forwarded to the ‘signin’ action in the Users controller. <?php
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function indexAction()
{
}
public function signinAction()
{
}
}
There is no limit on the “forwards” you can have in your application, so long as they do not result in circular references, at which point your application will halt. If there are no other actions to be dispatched by the dispatch loop, the dispatcher will automatically invoke the view layer of the MVC that is managed by Phalcon\Mvc\View. コントローラの初期化¶Phalcon\Mvc\Controller offers the <?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") {
// ...
}
}
}
If you want to execute some initialization logic just after the controller object is constructed then you can implement the
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function onConstruct()
{
// ...
}
}
サービスの注入¶If a controller extends Phalcon\Mvc\Controller then it has easy access to the service container in application. For example, if we have registered a service like this: <?php
use Phalcon\Di;
$di = new Di();
$di->set(
"storage",
function () {
return new Storage(
"/some/directory"
);
},
true
);
Then, we can access that service in several ways: <?php
use Phalcon\Mvc\Controller;
class FilesController extends Controller
{
public function saveAction()
{
// Injecting the service by just accessing the property with the same name
$this->storage->save("/some/file");
// Accessing the service from the DI
$this->di->get("storage")->save("/some/file");
// Another way to access the service using the magic getter
$this->di->getStorage()->save("/some/file");
// Another way to access the service using the magic getter
$this->getDi()->getStorage()->save("/some/file");
// Using the array-syntax
$this->di["storage"]->save("/some/file");
}
}
If you’re using Phalcon as a full-stack framework, you can read the services provided by default in the framework. リクエストとレスポンス¶Assuming that the framework provides a set of pre-registered services. We explain how to interact with the HTTP environment. The “request” service contains an instance of Phalcon\Http\Request and the “response” contains a Phalcon\Http\Response representing what is going to be sent back to the client. <?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");
}
}
}
The response object is not usually used directly, but is built up before the execution of the action, sometimes - like in an afterDispatch event - it can be useful to access the response directly: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function notFoundAction()
{
// Send a HTTP 404 response header
$this->response->setStatusCode(404, "Not Found");
}
}
Learn more about the HTTP environment in their dedicated articles request and response. セッションデータ¶Sessions help us maintain persistent data between requests. You can access a Phalcon\Session\Bag from any controller to encapsulate data that needs to be persistent: <?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¶Services may act as controllers, controllers classes are always requested from the services container. Accordingly, any other class registered with its name can easily replace a controller: <?php
// Register a controller as a service
$di->set(
"IndexController",
function () {
$component = new Component();
return $component;
}
);
// Register a namespaced controller as a service
$di->set(
"Backend\\Controllers\\IndexController",
function () {
$component = new Component();
return $component;
}
);
コントローラのイベント¶Controllers automatically act as listeners for dispatcher events, implementing methods with those event names allow you to implement hook points before/after the actions are executed: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function beforeExecuteRoute($dispatcher)
{
// This is executed before every found 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)
{
// Executed after every found action
}
}
モデルの働き¶モデルは、そのデータを操作するアプリケーションの情報 (データ) およびルールを表します。モデルは、主に、対応するデータベーステーブルとの相互作用のルールを管理するために使用されます。多くの場合、データベース内の各テーブルには、アプリケーション内の一つのモデルに対応します。アプリケーションのビジネスロジックの大部分は、モデルに集中するでしょう。 Phalcon\Mvc\Model は、Phalconアプリケーション内のすべてのモデルのためのベースとなっています。これは、データベースの独立性、基本的なCRUD機能、高度な検索機能、およびその他のサービスの中でお互いにモデルを関連付ける機能を提供します。 Phalcon\Mvc\Model は、それぞれのデータベースエンジン操作に動的にメソッドを変換するためのSQL文を使用することの必要性を避けています。
モデルの作成¶モデルは Phalcon\Mvc\Model から継承したクラスです。そのクラス名はキャメルケースで表記すべきです: <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
}
デフォルトでは、モデル “Store\Toys\RobotParts” はテーブル “robot_parts” を参照します。手動でマッピングテーブルに別の名前を指定したい場合は、 <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
public function initialize()
{
$this->setSource("toys_robot_parts");
}
}
モデル RobotParts は現在、「 toys_robot_parts 」テーブルにマップされています。上記の方法に加えて、
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class RobotParts extends Model
{
public function onConstruct()
{
// ...
}
}
パブリックプロパティ vs セッター/ゲッター¶モデルの各プロパティは、パブリックスコープで実装することができます、つまり、特に制限なく、モデルクラスがインスタンス化されたコードのどの部分からでも更新/読み取ることができることを意味します。 <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $price;
}
ゲッターとセッターを使用して、どのプロパティで目に見える公的データに様々な変換を行い、また、オブジェクトに格納されたデータに検証ルールを追加するか制御することができます: <?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)
{
// 名前が短すぎる?
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)
{
// マイナスの価格が許可されていません
if ($price < 0) {
throw new InvalidArgumentException(
"Price can't be negative"
);
}
$this->price = $price;
}
public function getPrice()
{
// 使用する前にdouble型に変換する
return (double) $this->price;
}
}
パブリックプロパティは、開発中の複雑さを少なくします。しかしゲッター/セッターは、アプリケーションのテスト容易性、拡張性と保守性を大きく向上させることができます。開発者は、作成しているアプリケーションに、より適している戦略を決定することができます。 ORMは定義するプロパティの両方の方式に対応しています。
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. レコードからオブジェクトを理解する¶モデルのすべてのインスタンスは、テーブル内の行を表します。あなたは簡単にオブジェクトのプロパティを読み取ることによってレコードデータにアクセスすることができます。例えば、”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;
// id = 3 を持つレコードを検索
$robot = Robots::findFirst(3);
// "Terminator" を出力
echo $robot->name;
レコードはメモリに入ると、そのデータに変更を加えてから、変更内容を保存することができます: <?php
use Store\Toys\Robots;
$robot = Robots::findFirst(3);
$robot->name = "RoboCop";
$robot->save();
ご覧のように、生のSQL文を使用する必要はありません。 Phalcon\Mvc\Model は、Webアプリケーションのための高いデータベース抽象化を提供します。 レコードの検索¶Phalcon\Mvc\Model もレコードを照会するためのいくつかのメソッドを提供しています。次の例では、モデルから1つまたは複数のレコードを照会する方法を紹介します: <?php
use Store\Toys\Robots;
// いくつの robots がありますか?
$robots = Robots::find();
echo "There are ", count($robots), "\n";
// いくつの mechanical robots がありますか?
$robots = Robots::find("type = 'mechanical'");
echo "There are ", count($robots), "\n";
// name 順に並べた virtual robots を取得し印刷
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// virtual robotsのname順の最初の100件を取得
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
"limit" => 100,
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
また、 <?php
use Store\Toys\Robots;
// robots テーブルの最初の robot は何ですか?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name, "\n";
// robots テーブルの最初の mechanical robot は何ですか?
$robot = Robots::findFirst("type = 'mechanical'");
echo "The first mechanical robot name is ", $robot->name, "\n";
// virtual robotsのname順の最初を取得
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual robot name is ", $robot->name, "\n";
<?php
use Store\Toys\Robots;
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name DESC",
"limit" => 30,
]
);
$robots = Robots::find(
[
"conditions" => "type = ?1",
"bind" => [
1 => "virtual",
]
]
);
利用可能なクエリオプションは次のとおり:
必要に応じて、パラメータの配列を使用する代わりに、オブジェクト指向の方法でクエリを作成する方法があります: <?php
use Store\Toys\Robots;
$robots = Robots::query()
->where("type = :type:")
->andWhere("year < 2000")
->bind(["type" => "mechanical"])
->order("name")
->execute();
静的メソッドの すべてのクエリは、内部で PHQL クエリとして処理されます。 PHQLは、高レベル、オブジェクト指向やSQLに似た言語です。この言語はあなたに他のモデルを結合するようなクエリを実行するための多くの機能を提供し、グループを定義し、集計などを追加します。 Lastly, there is the <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $id;
public $name;
public $price;
}
We have three properties to work with here: <?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 . ".";
}
Notice that we used ‘Name’ in the method call and passed the variable モデルの結果セット¶While These objects are more powerful than standard arrays. One of the greatest features of the Phalcon\Mvc\Model\Resultset is that at any time there is only one record in memory. This greatly helps in memory management especially when working with large amounts of data. <?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’s resultsets emulate scrollable cursors, you can get any row just by accessing its position, or seeking the internal pointer to a specific position. Note that some database systems don’t support scrollable cursors, this forces to re-execute the query in order to rewind the cursor to the beginning and obtain the record at the requested position. Similarly, if a resultset is traversed several times, the query must be executed the same number of times. As storing large query results in memory could consume many resources, resultsets are obtained from the database in chunks of 32 rows - reducing the need to re-execute the request in several cases. Note that resultsets can be serialized and stored in a cache backend. Phalcon\Cache can help with that task. However, serializing data causes Phalcon\Mvc\Model to retrieve all the data from the database in an array, thus consuming more memory while this process takes place. <?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;
}
結果セットのフィルタリング¶The most efficient way to filter data is setting some search criteria, databases will use indexes set on tables to return data faster. Phalcon additionally allows you to filter the data using PHP using any resource that is not available in the database: <?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;
}
}
);
パラメータの割り当て¶Bound parameters are also supported in Phalcon\Mvc\Model. You are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and integer placeholders are supported. Binding parameters can simply be achieved as follows: <?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",
],
]
);
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. Strings are automatically escaped using PDO. This function takes into account the connection charset, so its recommended to define the correct charset in the connection parameters or in the database configuration, as a wrong charset will produce undesired effects when storing or retrieving data. Additionally you can set the parameter “bindTypes”, this allows defining how the parameters should be bound according to its data type: <?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,
]
);
If you bind arrays in bound parameters, keep in mind, that keys must be numbered from zero: <?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
]
]
);
If you’re using “finders”, bound parameters are automatically used for you: <?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");
取得したレコードの初期化/準備¶May be the case that after obtaining a record from the database is necessary to initialise the data before
being used by the rest of the application. You can implement the <?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);
}
}
If you use getters/setters instead of/or together with public properties, you can initialize the field once it is accessed: <?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);
}
}
計算/集計の実行¶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",
]
);
レコードの作成、更新¶The 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);
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",
]
);
確実に作成/更新する¶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 <?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. レコードの削除¶The <?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:
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¶モデル間のリレーション¶There are four types of relationships: one-on-one, one-to-many, many-to-one and many-to-many. The relationship may be unidirectional or bidirectional, and each can be simple (a one to one model) or more complex (a combination of models). 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 relations are those that are generated in relation to one another but not vice versa. 双方向のリレーション¶The bidirectional relations build relationships in both models and each model defines the inverse relationship of the other. リレーションの定義¶In Phalcon, relationships must be defined in the
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`)
);
Check the EER diagram to understand better the relations: ![]() 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"
);
}
}
リレーションの活用¶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 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
<?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
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: ![]() 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;
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);
}
}
仮想外部キー¶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 <?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. 関連レコードの保存¶Magic properties can be used to store a record and its related properties: <?php
// Create an artist
$artist = new Artists();
$artist->name = "Shinichi Osawa";
$artist->country = "Japan";
// Create an album
$album = new Albums();
$album->name = "The One";
$album->artist = $artist; // Assign the artist
$album->year = 2008;
// Save both records
$album->save();
Saving a record and its related records in a has-many relation: <?php
// Get an existing artist
$artist = Artists::findFirst(
"name = 'Shinichi Osawa'"
);
// Create an album
$album = new Albums();
$album->name = "The One";
$album->artist = $artist;
$songs = [];
// Create a first song
$songs[0] = new Songs();
$songs[0]->name = "Star Guitar";
$songs[0]->duration = "5:54";
// Create a second song
$songs[1] = new Songs();
$songs[1]->name = "Last Days";
$songs[1]->duration = "4:29";
// Assign the songs array
$album->songs = $songs;
// Save the album + its songs
$album->save();
Saving the album and the artist at the same time implicitly makes use of a transaction so if anything goes wrong with saving the related records, the parent will not be saved either. Messages are passed back to the user for information regarding any errors. Note: Adding related entities by overloading the following methods is not possible:
You need to overload 結果セットの操作¶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: 関連するレコードの更新¶Instead of doing this: <?php
$parts = $robots->getParts();
foreach ($parts as $part) {
$part->stock = 100;
$part->updated_at = time();
if ($part->update() === false) {
$messages = $part->getMessages();
foreach ($messages as $message) {
echo $message;
}
break;
}
}
you can do this: <?php
$robots->getParts()->update(
[
"stock" => 100,
"updated_at" => time(),
]
);
‘update’ also accepts an anonymous function to filter what records must be updated: <?php
$data = [
"stock" => 100,
"updated_at" => time(),
];
// Update all the parts except those whose type is basic
$robots->getParts()->update(
$data,
function ($part) {
if ($part->type === Part::TYPE_BASIC) {
return false;
}
return true;
}
);
関連するレコードの削除¶Instead of doing this: <?php
$parts = $robots->getParts();
foreach ($parts as $part) {
if ($part->delete() === false) {
$messages = $part->getMessages();
foreach ($messages as $message) {
echo $message;
}
break;
}
}
you can do this: <?php
$robots->getParts()->delete();
<?php
// Delete only whose stock is greater or equal than zero
$robots->getParts()->delete(
function ($part) {
if ($part->stock < 0) {
return false;
}
return true;
}
);
Model Events¶イベントとイベント・マネージャ¶Models allow you to implement events that will be thrown while performing an insert/update/delete which can be used to define business rules. The following are the events supported by Phalcon\Mvc\Model and their order of execution:
モデルクラス内でのイベントの実装¶The easier way to make a model react to events is to 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 used 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");
}
}
カスタムイベントマネージャの使用¶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文のロギング¶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文のプロファイリング¶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:
タイムスタンプ化¶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. 論理削除¶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. 独自の振る舞いの作成¶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();
振る舞いとしてのトレイトの使用¶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;
}
モデルのメタデータ¶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);
メタデータのキャッシュ¶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:
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;
};
メタデータの取得方法¶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;
};
データベースの内部構造から取得する方法¶This strategy doesn’t require any customization and is implicitly used by all the metadata adapters. アノテーションによる方法¶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:
The annotation @Column supports the following parameters:
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;
};
手動によるメタデータの管理¶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¶When a process performs multiple database operations, it might be important that each step is completed successfully so that data integrity can be maintained. Transactions offer the ability to ensure that all database operations have been executed successfully before the data is committed to the database. Transactions in Phalcon allow you to commit all operations if they were executed successfully or rollback all operations if something went wrong. 手動のトランザクション¶If an application only uses one connection and the transactions aren’t very complex, a transaction can be created by just moving the current connection into transaction mode and then commit or rollback the operation whether it is successful or not: <?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();
}
}
暗黙的なトランザクション¶Existing relationships can be used to store records and their related instances, this kind of operation implicitly creates a transaction to ensure that data is correctly stored: <?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¶Isolated transactions are executed in a new connection ensuring that all the generated SQL, virtual foreign key checks and business rules are isolated from the main connection. This kind of transaction requires a transaction manager that globally manages each transaction created ensuring that they are correctly rolled back/committed before ending the request: <?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();
}
Transactions can be used to delete many records in a consistent way: <?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();
}
Transactions are reused no matter where the transaction object is retrieved. A new transaction is generated only when a <?php
use Phalcon\Mvc\Model\Transaction\Manager as TransactionManager
$di->setShared(
"transactions",
function () {
return new TransactionManager();
}
);
Then access it from a controller or view: <?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();
// ...
}
}
While a transaction is active, the transaction manager will always return the same transaction across the application. Validating Models¶データ整合性の検証¶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.
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;
}
}
バリデーション・メッセージ¶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 <?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:
The <?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;
}
}
バリデーション失敗のイベント¶Another type of events are available when the data validation process finds any inconsistency:
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;
}
自動採番のIDカラム¶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 <?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");
}
}
}
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:
The independent column map allow you to:
レコードのスナップショット¶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
別のスキーマの指定¶If a model is mapped to a table that is in a different schemas/databases than the default. You can use the <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setSchema("toys");
}
}
複数のデータベースの設定¶In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when
Phalcon\Mvc\Model needs to connect to the database it requests the “db” service
in the application’s services container. You can overwrite this service setting it in the <?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",
]
);
}
);
Then, in the <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setConnectionService("dbPostgres");
}
}
But Phalcon offers you more flexibility, you can define the connection that must be used to ‘read’ and for ‘write’. This is specially useful to balance the load to your databases implementing a master-slave architecture: <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setReadConnectionService("dbSlave");
$this->setWriteConnectionService("dbMaster");
}
}
The ORM also provides Horizontal Sharding facilities, by allowing you to implement a ‘shard’ selection according to the current query conditions: <?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");
}
}
The <?php
use Store\Toys\Robots;
$robot = Robots::findFirst('id = 101');
Injecting services into Models¶You may be required to access the application services within a model, the following example explains how to do that: <?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);
}
}
}
The “notSaved” event is triggered every time that a “create” or “update” action fails. So we’re flashing the validation messages obtaining the “flash” service from the DI container. By doing this, we don’t have to print messages after each save. 機能の無効化/有効化¶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:
スタンドアロン・コンポーネント¶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クエリランゲージ (PHQL)¶Phalcon Query Language, PhalconQL or simply PHQL is a high-level, object-oriented SQL dialect that allows to write queries using a standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. To achieve the highest performance possible, Phalcon provides a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe. 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:
使用例¶To better explain how PHQL works consider the following example. We have two models “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");
}
}
And every Car has a Brand, so a Brand has many Cars: <?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クエリの作成¶PHQL queries can be created just by instantiating the class 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();
From a controller or a view, it’s easy to create/execute them using an injected models manager: <?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",
]
);
Or simply execute it: <?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",
]
);
レコードのセレクト¶As the familiar SQL, PHQL allows querying of records using the SELECT statement we know, except that instead of specifying tables, we use the models classes: <?php
$query = $manager->createQuery(
"SELECT * FROM Cars ORDER BY Cars.name"
);
$query = $manager->createQuery(
"SELECT Cars.name FROM Cars ORDER BY Cars.name"
);
Classes in namespaces are also allowed: <?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);
Most of the SQL standard is supported by PHQL, even nonstandard directives such as 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);
結果タイプ¶Depending on the type of columns we query, the result type will vary. If you retrieve a single whole object, then the object returned is a Phalcon\Mvc\Model\Resultset\Simple. This kind of resultset is a set of complete model objects: <?php
$phql = "SELECT c.* FROM Cars AS c ORDER BY c.name";
$cars = $manager->executeQuery($phql);
foreach ($cars as $car) {
echo "Name: ", $car->name, "\n";
}
This is exactly the same as: <?php
$cars = Cars::find(
[
"order" => "name"
]
);
foreach ($cars as $car) {
echo "Name: ", $car->name, "\n";
}
Complete objects can be modified and re-saved in the database because they represent a complete record of the associated table. There are other types of queries that do not return complete objects, for example: <?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";
}
We are only requesting some fields in the table, therefore those cannot be considered an entire object, so the returned object is still a resultset of type Phalcon\Mvc\Model\Resultset\Simple. However, each element is a standard object that only contain the two columns that were requested. 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. 表結合(JOIN)¶It’s easy to request records from multiple models using PHQL. Most kinds of Joins are supported. 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);
It is also possible to manually set the conditions of the 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'
集約¶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 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"
]
);
データの追加¶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 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:
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();
データの削除¶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();
}
}
クエリビルダを使用したクエリの作成¶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 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]);
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 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. 予約語のエスケープ¶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 ライフサイクル¶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:
生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
]
);
トラブルシューティング¶Some things to keep in mind when using PHQL:
ORMにおけるキャッシュ¶Every application is different, we could have models whose data change frequently and others that rarely change. Accessing database systems is often one of the most common bottlenecks in terms of performance. This is due to the complex connection/communication processes that PHP must do in each request to obtain data from the database. Therefore, if we want to achieve good performance we need to add some layers of caching where the application requires it. This chapter explains the possible points where it is possible to implement caching to improve performance. The framework gives you the tools to implement the cache where you demand of it according to the architecture of your application. 結果セットのキャッシュ¶A well established technique to avoid continuously accessing to the database is to cache resultsets that don’t change frequently using a system with faster access (usually memory). When Phalcon\Mvc\Model requires a service to cache resultsets, it will request it to the Dependency Injector Container with the convention name “modelsCache”. As Phalcon provides a component to cache any kind of data, we’ll explain how to integrate it with Models. First, you must register it as a service in the services container: <?php
use Phalcon\Cache\Frontend\Data as FrontendData;
use Phalcon\Cache\Backend\Memcache as BackendMemcache;
// Set the models cache service
$di->set(
"modelsCache",
function () {
// Cache data for one day by default
$frontCache = new FrontendData(
[
"lifetime" => 86400,
]
);
// Memcached connection settings
$cache = new BackendMemcache(
$frontCache,
[
"host" => "localhost",
"port" => "11211",
]
);
return $cache;
}
);
You have complete control in creating and customizing the cache before being used by registering the service as an anonymous function. Once the cache setup is properly defined you could cache resultsets as follows: <?php
// Get products without caching
$products = Products::find();
// Just cache the resultset. The cache will expire in 1 hour (3600 seconds)
$products = Products::find(
[
"cache" => [
"key" => "my-cache",
],
]
);
// Cache the resultset for only for 5 minutes
$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",
"service" => "cache",
],
]
);
Caching could be also applied to resultsets generated using relationships: <?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,
],
]
);
When a cached resultset needs to be invalidated, you can simply delete it from the cache using the previously specified key. Note that not all resultsets should be cached. Results that change very frequently should not be cached since they are invalidated very quickly and caching in that case impacts performance. Additionally, large datasets that do not change frequently could be cached, but that is a decision that the developer has to make based on the available caching mechanism and whether the performance impact to simply retrieve that data in the first place is acceptable. キャッシュの強制¶Earlier we saw how Phalcon\Mvc\Model integrates with the caching component provided by the framework. To make a record/resultset cacheable we pass the key ‘cache’ in the array of parameters: <?php
// Cache the resultset for only for 5 minutes
$products = Products::find(
[
"cache" => [
"key" => "my-cache",
"lifetime" => 300,
],
]
);
This gives us the freedom to cache specific queries, however if we want to cache globally every query performed over the model,
we can override the <?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)
{
// ...
}
}
Accessing the database is several times slower than calculating a cache key. You’re free to implement any key generation strategy you find to better for your needs. Note that a good key avoids collisions as much as possible - meaning that different keys should return unrelated records. This gives you full control on how the cache should be implemented for each model. If this strategy is common to several models you can create a base class for all of them: <?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
}
}
Then use this class as base class for each ‘Cacheable’ model: <?php
class Robots extends CacheableModel
{
}
PHQLクエリのキャッシュ¶Regardless of the syntax we used to create them, all queries in the ORM are handled internally using PHQL. This language gives you much more freedom to create all kinds of queries. Of course these queries can be cached: <?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",
]
);
再利用可能な関連レコード¶Some models may have relationships with other models. This allows us to easily check the records that relate to instances in memory: <?php
// Get some invoice
$invoice = Invoices::findFirst();
// Get the customer related to the invoice
$customer = $invoice->customer;
// Print his/her name
echo $customer->name, "\n";
This example is very simple, a customer is queried and can be used as required, for example, to show its name. This also applies if we retrieve a set of invoices to show customers that correspond to these invoices: <?php
// Get a set of invoices
// SELECT * FROM invoices;
$invoices = Invoices::find();
foreach ($invoices as $invoice) {
// Get the customer related to the invoice
// SELECT * FROM customers WHERE id = ?;
$customer = $invoice->customer;
// Print his/her name
echo $customer->name, "\n";
}
A customer may have one or more bills so, in this example, the same customer record may be unnecessarily queried several times. To avoid this, we could mark the relationship as reusable; by doing so, we tell the ORM to automatically reuse the records from memory instead of re-querying them again and again: <?php
use Phalcon\Mvc\Model;
class Invoices extends Model
{
public function initialize()
{
$this->belongsTo(
"customers_id",
"Customer",
"id",
[
"reusable" => true,
]
);
}
}
Note that this type of cache works in memory only, this means that cached data are released when the request is terminated. 関連するレコードのキャッシュ¶When a related record is queried, the ORM internally builds the appropriate condition and gets the required records using
This means that when you get a related record you could intercept how the data is obtained by implementing the corresponding method: <?php
// Get some invoice
$invoice = Invoices::findFirst();
// Get the customer related to the invoice
$customer = $invoice->customer; // Invoices::findFirst("...");
// Same as above
$customer = $invoice->getCustomer(); // Invoices::findFirst("...");
Accordingly, we could replace the <?php
use Phalcon\Mvc\Model;
class Invoices extends Model
{
public static function findFirst($parameters = null)
{
// ... Custom caching strategy
}
}
関連するレコードの再帰的なキャッシュ¶In this scenario, we assume that every time we query a result we also retrieve their associated records. If we store the records found together with their related entities perhaps we could reduce a bit the overhead required to obtain all entities: <?php
use Phalcon\Mvc\Model;
class Invoices extends Model
{
protected static function _createKey($parameters)
{
// ... Create a cache key based on the parameters
}
protected static function _getCache($key)
{
// Returns data from a cache
}
protected static function _setCache($key, $results)
{
// Stores data in the cache
}
public static function find($parameters = null)
{
// Create a unique key
$key = self::_createKey($parameters);
// Check if there are data in the cache
$results = self::_getCache($key);
// Valid data is an object
if (is_object($results)) {
return $results;
}
$results = [];
$invoices = parent::find($parameters);
foreach ($invoices as $invoice) {
// Query the related customer
$customer = $invoice->customer;
// Assign it to the record
$invoice->customer = $customer;
$results[] = $invoice;
}
// Store the invoices in the cache + their customers
self::_setCache($key, $results);
return $results;
}
public function initialize()
{
// Add relations and initialize other stuff
}
}
Getting the invoices from the cache already obtains the customer data in just one hit, reducing the overall overhead of the operation. Note that this process can also be performed with PHQL following an alternative solution: <?php
use Phalcon\Mvc\Model;
class Invoices extends Model
{
public function initialize()
{
// Add relations and initialize other stuff
}
protected static function _createKey($conditions, $params)
{
// ... Create a cache key based on the parameters
}
public function getInvoicesCustomers($conditions, $params = null)
{
$phql = "SELECT Invoices.*, Customers.* FROM Invoices JOIN Customers WHERE " . $conditions;
$query = $this->getModelsManager()->executeQuery($phql);
$query->cache(
[
"key" => self::_createKey($conditions, $params),
"lifetime" => 300,
]
);
return $query->execute($params);
}
}
条件にもとづくキャッシュ¶In this scenario, the cache is implemented differently depending on the conditions received. We might decide that the cache backend should be determined by the primary key:
The easiest way is adding a static method to the model that chooses the right cache to be used: <?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,
],
]
);
}
}
This approach solves the problem, however, if we want to add other parameters such orders or conditions we would have to create
a more complicated method. Additionally, this method does not work if the data is obtained using related records or a <?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",
]
);
To achieve this we need to intercept the intermediate representation (IR) generated by the PHQL parser and thus customize the cache everything possible: The first is create a custom builder, so we can generate a totally customized query: <?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;
}
}
Instead of directly returning a Phalcon\Mvc\Model\Query, our custom builder returns a CustomQuery instance, this class looks like: <?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;
}
}
Implementing a helper (CustomNodeVisitor) that recursively checks the conditions looking for fields that tell us the possible range to be used in the cache: <?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;
}
}
Finally, we can replace the find method in the Robots model to use the custom classes we’ve created: <?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実行計画のキャッシュ¶As well as most moderns database systems PHQL internally caches the execution plan, if the same statement is executed several times PHQL reuses the previously generated plan improving performance, for a developer to take better advantage of this is highly recommended build all your SQL statements passing variable parameters as bound parameters: <?php
for ($i = 1; $i <= 10; $i++) {
$phql = "SELECT * FROM Store\Robots WHERE id = " . $i;
$robots = $this->modelsManager->executeQuery($phql);
// ...
}
In the above example, ten plans were generated increasing the memory usage and processing in the application. Rewriting the code to take advantage of bound parameters reduces the processing by both ORM and database system: <?php
$phql = "SELECT * FROM Store\Robots WHERE id = ?0";
for ($i = 1; $i <= 10; $i++) {
$robots = $this->modelsManager->executeQuery(
$phql,
[
$i,
]
);
// ...
}
Performance can be also improved reusing the PHQL query: <?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,
]
);
// ...
}
Execution plans for queries involving prepared statements are also cached by most database systems reducing the overall execution time, also protecting your application against SQL Injections. ODM (Object-Document Mapper)¶In addition to its ability to map tables in relational databases, Phalcon can map documents from NoSQL databases. The ODM offers a CRUD functionality, events, validations among other services. Due to the absence of SQL queries and planners, NoSQL databases can see real improvements in performance using the Phalcon approach. Additionally, there are no SQL building reducing the possibility of SQL injections. The following NoSQL databases are supported:
モデルの作成¶A model is a class that extends from Phalcon\Mvc\Collection. It must be placed in the models directory. A model file must contain a single class; its class name should be in camel case notation: <?php
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
}
By default model “Robots” will refer to the collection “robots”. If you want to manually specify another name for the mapping collection,
you can use the <?php
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
public function initialize()
{
$this->setSource("the_robots");
}
}
Understanding Documents To Objects¶Every instance of a model represents a document in the collection. You can easily access collection data by reading object properties. For example, for a collection “robots” with the documents: $ 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 }
>
名前空間内のモデル¶Namespaces can be used to avoid class name collision. In this case it is necessary to indicate the name of the related collection using the <?php
namespace Store\Toys;
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
public function initialize()
{
$this->setSource("robots");
}
}
You could find a certain document by its ID and then print its name: <?php
// Find record with _id = "5087358f2d42b8c3d15ec4e2"
$robot = Robots::findById("5087358f2d42b8c3d15ec4e2");
// Prints "Bender"
echo $robot->name;
Once the record is in memory, you can make modifications to its data and then save changes: <?php
$robot = Robots::findFirst(
[
[
"name" => "Astro Boy",
]
]
);
$robot->name = "Voltron";
$robot->save();
接続設定¶Connections are retrieved from the services container. By default, Phalcon tries to find the connection in a service called “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
);
ドキュメントの検索¶As Phalcon\Mvc\Collection relies on the Mongo PHP extension you have the same facilities to query documents and convert them transparently to model instances: <?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";
}
You could also use the <?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";
Both <?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,
],
]
);
The available query options are:
If you have experience with SQL databases, you may want to check the SQL to Mongo Mapping Chart. 集計¶A model can return calculations using aggregation framework provided by Mongo. The aggregated values are calculate without having to use MapReduce. With this option is easy perform tasks such as totaling or averaging field values: <?php
$data = Article::aggregate(
[
[
"\$project" => [
"category" => 1,
],
],
[
"\$group" => [
"_id" => [
"category" => "\$category"
],
"id" => [
"\$max" => "\$_id",
],
],
],
]
);
レコードの作成、更新¶The Also the method executes associated validators and events that are defined in the model: <?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!";
}
The “_id” property is automatically updated with the MongoId object created by the driver: <?php
$robot->save();
echo "The generated id is: ", $robot->getId();
バリデーション・メッセージ¶Phalcon\Mvc\Collection has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes. Each message consists of an instance of the class Phalcon\Mvc\Model\Message. The set of messages generated can be retrieved with the method getMessages(). 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();
}
}
バリデーション・イベントとイベント・マネージャ¶Models allow you to implement events that will be thrown when performing an insert or update. They help define business rules for a certain model. The following are the events supported by Phalcon\Mvc\Collection and their order of execution:
To make a model to react to an event, we must to implement a method with the same name of the event: <?php
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
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\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");
}
}
Additionally, this component is integrated with Phalcon\Events\Manager, this means we can create listeners that run when an event is triggered. <?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();
In the example given above the EventsManager only acted as a bridge between an object and a listener (the anonymous function). If we want all objects created in our application use the same EventsManager, then we need to assign this to the Models Manager: <?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
);
ビジネス・ルールの実装¶When an insert, update or delete is executed, the model verifies if there are any methods with the names of the events listed in the table above. We recommend that validation methods are declared protected to prevent that business logic implementation from being exposed publicly. The following example implements an event that validates the year cannot be smaller than 0 on update or insert: <?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;
}
}
}
Some events return false as an indication to stop the current operation. If an event doesn’t return anything, Phalcon\Mvc\Collection will assume a true value. データ整合性の検証¶Phalcon\Mvc\Collection 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
use Phalcon\Mvc\Collection;
use Phalcon\Validation;
use Phalcon\Validation\Validator\InclusionIn;
use Phalcon\Validation\Validator\Numericality;
class Robots extends Collection
{
public function validation()
{
$validation = new Validation();
$validation->add(
"type",
new InclusionIn(
[
"message" => "Type must be: mechanical or virtual",
"domain" => [
"Mechanical",
"Virtual",
],
]
)
);
$validation->add(
"price",
new Numericality(
[
"message" => "Price must be numeric"
]
)
);
return $this->validate($validation);
}
}
The example given above 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.
レコードの削除¶The <?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!";
}
}
You can also delete many documents by traversing a resultset with a <?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!";
}
}
The following events are available to define custom business rules that can be executed when a delete operation is performed:
バリデーション失敗のイベント¶Another type of events is available when the data validation process finds any inconsistency:
暗黙のID VS. ユーザー指定プライマリキー¶By default Phalcon\Mvc\Collection assumes that the <?php
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
public function initialize()
{
$this->useImplicitObjectIds(false);
}
}
複数のデータベースの設定¶In Phalcon, all models can belong to the same database connection or have an individual one. Actually, when Phalcon\Mvc\Collection needs to connect to the database it requests the “mongo” service in the application’s services container. You can overwrite this service setting it in the initialize method: <?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
);
Then, in the <?php
use Phalcon\Mvc\Collection;
class Robots extends Collection
{
public function initialize()
{
$this->setConnectionService("mongo1");
}
}
モデルにサービスを注入する¶You may be required to access the application services within a model, the following example explains how to do that: <?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
);
}
}
}
The “notSave” event is triggered whenever a “creating” or “updating” action fails. We’re flashing the validation messages obtaining the “flash” service from the DI container. By doing this, we don’t have to print messages after each saving. Viewの使用¶Views represent the user interface of your application. Views are often HTML files with embedded PHP code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application. Phalcon\Mvc\View and Phalcon\Mvc\View\Simple are responsible for the managing the view layer of your MVC application. コントローラとビューの結合¶Phalcon automatically passes the execution to the view component as soon as a particular controller has completed its cycle. The view component will look in the views folder for a folder named as the same name of the last controller executed and then for a file named as the last action executed. For instance, if a request is made to the URL http://127.0.0.1/blog/posts/show/301, Phalcon will parse the URL as follows:
The dispatcher will look for a “PostsController” and its action “showAction”. A simple controller file for this example: <?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;
}
}
The 階層的なレンダリング¶Phalcon\Mvc\View supports a hierarchy of files and is the default component for view rendering in Phalcon. This hierarchy allows for common layout points (commonly used views), as well as controller named folders defining respective view templates. This component uses by default PHP itself as the template engine, therefore views should have the .phtml extension. If the views directory is app/views then view component will find automatically for these 3 view files.
You are not required to implement all of the files mentioned above. Phalcon\Mvc\View will simply move to the next view level in the hierarchy of files. If all three view files are implemented, they will be processed as follows: <!-- 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>
Note the lines where the method ![]() The generated HTML by the request will be: <!-- 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>
テンプレートの使用¶Templates are views that can be used to share common view code. They act as controller layouts, so you need to place them in the layouts directory. Templates can be rendered before the layout (using <?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>
The final output will be the following: <!-- 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>
If we had used <!-- 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>
レンダリングレベルのコントロール¶As seen above, Phalcon\Mvc\View supports a view hierarchy. You might need to control the level of rendering
produced by the view component. The method This method can be invoked from the controller or from a superior view layer to interfere with the rendering process. <?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
);
}
}
The available render levels are:
レンダリング レベルの無効化¶You can permanently or temporarily disable render levels. A level could be permanently disabled if it isn’t used at all in the whole application: <?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
);
Or disable temporarily in some part of the application: <?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¶As mentioned above, when Phalcon\Mvc\View is managed by Phalcon\Mvc\Application
the view rendered is the one related with the last controller and action executed. You could override this by using the <?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",
]
);
}
}
Viewの無効化¶If your controller doesn’t produce any output in the view (or not even have one) you may disable the view component avoiding unnecessary processing: <?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 <?php
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function closeSessionAction()
{
// ...
// Disable the view to avoid rendering
return false;
}
}
You can return a ‘response’ object to avoid disable the view manually: <?php
use Phalcon\Mvc\Controller;
class UsersController extends Controller
{
public function closeSessionAction()
{
// Close session
// ...
// A HTTP Redirect
return $this->response->redirect("index/index");
}
}
簡単なレンダリング¶Phalcon\Mvc\View\Simple is an alternative component to Phalcon\Mvc\View. It keeps most of the philosophy of Phalcon\Mvc\View but lacks of a hierarchy of files which is, in fact, the main feature of its counterpart. This component allows the developer to have control of when a view is rendered and its location. In addition, this component can leverage of view inheritance available in template engines such as Volt and others. The default component must be replaced in the service container: <?php
use Phalcon\Mvc\View\Simple as SimpleView;
$di->set(
"view",
function () {
$view = new SimpleView();
$view->setViewsDir("../app/views/");
return $view;
},
true
);
Automatic rendering must be disabled in Phalcon\Mvc\Application (if needed): <?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();
}
To render a view it’s necessary to call the render method explicitly indicating the relative path to the view you want to display: <?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 <?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);
パーシャルの使用¶Partial templates are another way of breaking the rendering process into simpler more manageable chunks that can be reused by different parts of the application. With a partial, you can move the code for rendering a particular piece of a response to its own file. One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that your code can be more easily understood. For example, you might have a view that looks like this: <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>
The <?php $this->partial("shared/ad_banner", ["id" => $site->id, "size" => "big"]); ?>
コントローラからViewへの値の受け渡し¶Phalcon\Mvc\View is available in each controller using the view variable ( <?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,
]
);
}
}
A variable with the name of the first parameter of <h1>
{{ username }}'s Posts
</h1>
<div class="post">
<?php
foreach ($posts as $post) {
echo "<h2>", $post->title, "</h2>";
}
?>
</div>
View断片のキャッシュ¶Sometimes when you develop dynamic websites and some areas of them are not updated very often, the output is exactly the same between requests. Phalcon\Mvc\View offers caching a part or the whole rendered output to increase performance. Phalcon\Mvc\View integrates with Phalcon\Cache to provide an easier way to cache output fragments. You could manually set the cache handler or set a global handler: <?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",
]
);
}
}
When we do not define a key to the cache, the component automatically creates one using an MD5 hash of the name of the controller and view currently being rendered in the format of “controller/view”. It is a good practice to define a key for each action so you can easily identify the cache associated with each view. When the View component needs to cache something it will request a cache service from the services container. The service name convention for this service is “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;
}
);
When using views, caching can be used to prevent controllers from needing to generate view data on each request. To achieve this we must identify uniquely each cache with a key. First we verify that the cache does not exist or has expired to make the calculations/queries to display data in the view: <?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",
]
);
}
}
The PHP alternative site is an example of implementing the caching of fragments. テンプレートエンジン¶Template Engines help designers to create views without the use of a complicated syntax. Phalcon includes a powerful and fast templating engine called Volt. Additionally, Phalcon\Mvc\View allows you to use other template engines instead of plain PHP or Volt. Using a different template engine, usually requires complex text parsing using external PHP libraries in order to generate the final output for the user. This usually increases the number of resources that your application will use. If an external template engine is used, Phalcon\Mvc\View provides exactly the same view hierarchy and it’s still possible to access the API inside these templates with a little more effort. This component uses adapters, these help Phalcon to speak with those external template engines in a unified way, let’s see how to do that integration. 独自のテンプレートエンジンアダプタの作成¶There are many template engines, which you might want to integrate or create one of your own. The first step to start using an external template engine is create an adapter for it. A template engine adapter is a class that acts as bridge between Phalcon\Mvc\View and the template engine itself.
Usually it only needs two methods implemented: The method <?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
// ...
}
}
テンプレートエンジンの変更¶You can replace the template engine completely or use more than one template engine at the same time. The method The order that the template engines are defined with If you want to register a template engine or a set of them for each request in the application. You could register it when the view service is created: <?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
);
There are adapters available for several template engines on the Phalcon Incubator Injecting services in View¶Every view executed is included inside a Phalcon\Di\Injectable instance, providing easy access to the application’s service container. The following example shows how to write a jQuery ajax request using a URL with the framework conventions. The service “url” (usually Phalcon\Mvc\Url) is injected in the view by accessing a property with the same name: <script type="text/javascript">
$.ajax({
url: "<?php echo $this->url->get("cities/get"); ?>"
})
.done(function () {
alert("Done!");
});
</script>
スタンドアロンコンポーネント¶All the components in Phalcon can be used as glue components individually because they are loosely coupled to each other: 階層的なレンダリング¶Using Phalcon\Mvc\View in a stand-alone mode can be demonstrated below: <?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();
A short syntax is also available: <?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
);
}
);
簡単なレンダリング¶Using Phalcon\Mvc\View\Simple in a stand-alone mode can be demonstrated below: <?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 イベント¶Phalcon\Mvc\View and Phalcon\Mvc\View\Simple are able to send events to an EventsManager if it is present. Events are triggered using the type “view”. Some events when returning boolean false could stop the active operation. The following events are supported:
The following example demonstrates how to attach listeners to this component: <?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
);
The following example shows how to create a plugin that clean/repair the HTML produced by the render process using Tidy: <?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()
);
View Helpers (Tags)¶Writing and maintaining HTML markup can quickly become a tedious task because of the naming conventions and numerous attributes that have to be taken into consideration. Phalcon deals with this complexity by offering Phalcon\Tag, which in turn offers view helpers to generate HTML markup. This component can be used in a plain HTML+PHP view or in a Volt template.
コンテンツのドキュメントタイプ¶Phalcon provides Available document type constants in Phalcon\Tag namespace are:
Setting document type. <?php
use Phalcon\Tag;
$this->tag->setDoctype(Tag::HTML401_STRICT);
?>
Getting document type. <?= $this->tag->getDoctype() ?>
<html>
<!-- your HTML code -->
</html>
The following HTML will be produced. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<!-- your HTML code -->
</html>
Volt syntax: {{ get_doctype() }}
<html>
<!-- your HTML code -->
</html>
リンクの作成¶A real common task in any web application or website is to produce links that allow us to navigate from one page to another. When they are internal URLs we can create them in the following manner: <!-- for the default route -->
<?= $this->tag->linkTo("products/search", "Search") ?>
<!-- with CSS attributes -->
<?= $this->tag->linkTo(["products/edit/10", "Edit", "class" => "edit-btn"]) ?>
<!-- for a named route -->
<?= $this->tag->linkTo([["for" => "show-product", "title" => 123, "name" => "carrots"], "Show"]) ?>
Actually, all produced URLs are generated by the component Phalcon\Mvc\Url (or service “url” failing) Same links generated with Volt: <!-- for the default route -->
{{ link_to("products/search", "Search") }}
<!-- for a named route -->
{{ link_to(["for": "show-product", "id": 123, "name": "carrots"], "Show") }}
<!-- for a named route with a HTML class -->
{{ link_to(["for": "show-product", "id": 123, "name": "carrots"], "Show", "class": "edit-btn") }}
フォームの作成¶Forms in web applications play an essential part in retrieving user input. The following example shows how to implement a simple search form using view helpers: <!-- 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() ?>
This last code will generate the following 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>
Same form generated in 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 also provides a form builder to create forms in an object-oriented manner. フォーム要素を生成するヘルパー¶Phalcon provides a series of helpers to generate form elements such as text fields, buttons and more. The first parameter of each helper is always the name of the element to be generated. When the form is submitted, the name will be passed along with the form data. In a controller you can get these values using the same name by using the <?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 syntax: {{ 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") }}
セレクトボックスの作成¶Generating select boxes (select box) is easy, especially if the related data is stored in PHP associative arrays. The helpers for select elements are <?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",
]
]
);
The following HTML will generated: <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>
You can add an “empty” option to the generated 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,
]
);
Produces this 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 syntax for above example: {# 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属性の割り当て¶All the helpers accept an array as their first parameter which can contain additional HTML attributes for the element generated. <?php $this->tag->textField(
[
"price",
"size" => 20,
"maxlength" => 30,
"placeholder" => "Enter a price",
]
) ?>
or using Volt: {{ text_field("price", "size": 20, "maxlength": 30, "placeholder": "Enter a price") }}
The following HTML is generated: <input type="text" name="price" id="price" size="20" maxlength="30"
placeholder="Enter a price" />
ヘルパーへの値の設定¶コントローラで設定する¶It is a good programming principle for MVC frameworks to set specific values for form elements in the view.
You can set those values directly from the controller using <?php
use Phalcon\Mvc\Controller;
class ProductsController extends Controller
{
public function indexAction()
{
$this->tag->setDefault("color", "Blue");
}
}
At the view, a selectStatic helper matches the same index used to preset the value. In this case “color”: <?php
echo $this->tag->selectStatic(
[
"color",
[
"Yellow" => "Yellow",
"Blue" => "Blue",
"Red" => "Red",
]
]
);
This will generate the following select tag with the value “Blue” selected: <select id="color" name="color">
<option value="Yellow">Yellow</option>
<option value="Blue" selected="selected">Blue</option>
<option value="Red">Red</option>
</select>
リクエストから設定する¶A special feature that the Phalcon\Tag helpers have is that they keep the values of form helpers between requests. This way you can easily show validation messages without losing entered data. 直接 値を設定する¶Every form helper supports the parameter “value”. With it you can specify a value for the helper directly. When this parameter is present, any preset value using setDefault() or via request will be ignored. ドキュメントのタイトルを動的に変更する¶Phalcon\Tag offers helpers to change dynamically the document title from the controller. The following example demonstrates just that: <?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>
The following HTML will generated: <html>
<head>
<title>Index of Posts - Your Website</title>
</head>
<body>
</body>
</html>
静的コンテンツヘルパー¶Phalcon\Tag also provide helpers to generate tags such as script, link or img. They aid in quick and easy generation of the static resources of your application 画像¶<?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 syntax: {# 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") }}
スタイルシート¶<?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 syntax: {# 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 syntax: {# 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 の要素 - 一般的なHTMLヘルパー¶Phalcon offers a generic HTML helper that allows the generation of any kind of HTML element. It is up to the developer to produce a valid HTML element name to the helper. <?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 syntax: {# 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") }}
タグ サービス¶Phalcon\Tag is available via the ‘tag’ service, this means you can access it from any part of the application where the services container is located: <?php echo $this->tag->linkTo("pages/about", "About") ?>
You can easily add new helpers to a custom component replacing the service ‘tag’ in the services container: <?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)
{
// ...
}
}
Then change the definition of the service ‘tag’: <?php
$di["tag"] = function () {
return new MyTags();
};
独自ヘルパーの作成¶You can easily create your own helpers. First, start by creating a new folder within the same directory as your controllers and models. Give it a title that is relative to what you are creating. For our example here, we can call it “customhelpers”. Next we will create a new file titled <?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;
}
}
After creating our custom helper, we will autoload the new directory that contains our helper class from our “index.php” located in the public directory. <?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();
}
Now you are ready to use your new helper within your views: <body>
<?php
echo MyTags::audioField(
[
"name" => "test",
"id" => "audio_test",
"src" => "/path/to/audio.mp3",
]
);
?>
</body>
In next chapter, we’ll talk about Volt a faster template engine for PHP, where you can use a more friendly syntax for using helpers provided by Phalcon\Tag. アセット管理¶
Phalcon\Assets\Manager はサービスコンテナで使用可能で、コンテナが使用可能などの場所からもリソースを追加することが出来ます。 リソースの追加¶Assets は CSS と JavaScript をビルトインリソースとしてサポートしています。必要であれば他のリソースを作成することが出来ます。Assets Manager はデフォルトで 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>素晴らしいウェブサイトたち</title>
<?php $this->assets->outputCss(); ?>
</head>
<body>
<!-- ... -->
<?php $this->assets->outputJs(); ?>
</body>
<html>
Volt で書くと: <html>
<head>
<title>素晴らしいウェブサイトたち</title>
{{ assets.outputCss() }}
</head>
<body>
<!-- ... -->
{{ assets.outputJs() }}
</body>
<html>
ページ読み込みパフォーマンス向上のため、JavaScript は ローカル/リモートリソース¶ローカルリソースは同じアプリケーションのドキュメントルートに配備されたものです。ローカルリソースの URL は url サービスによって生成されます(通常は Phalcon\Mvc\Url )。 リモートリソースは CDN から提供される、jQuery や Bootstrap のようなライブラリです。
<?php
public function indexAction()
{
// ローカル CSS リソースの追加
$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");
}
コレクション¶コレクションは同じ種類のリソースをグループ化します。Assets Manager は暗黙的に css と js のコレクションを生成します。ビューへの配置を容易にするために、特定のリソースをグループ化するコレクションを追加することが出来ます。 <?php
// head 部分に配置予定の JavaScript
$headerCollection = $this->assets->collection("header");
$headerCollection->addJs("js/jquery.js");
$headerCollection->addJs("js/bootstrap.min.js");
// HTML 末尾に配置予定の JavaScript
$footerCollection = $this->assets->collection("footer");
$footerCollection->addJs("js/jquery.js");
$footerCollection->addJs("js/bootstrap.min.js");
ビューへ配置: <html>
<head>
<title>素晴らしいウェブサイトたち</title>
<?php $this->assets->outputJs("header"); ?>
</head>
<body>
<!-- ... -->
<?php $this->assets->outputJs("footer"); ?>
</body>
<html>
Volt で書くと: <html>
<head>
<title>素晴らしいウェブサイトたち</title>
{{ assets.outputCss("header") }}
</head>
<body>
<!-- ... -->
{{ assets.outputJs("footer") }}
</body>
<html>
プレフィックス¶コレクションは URL のプレフィックスを付けることができ、簡単に配信元のサーバを切り替えることができます。 <?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");
圧縮/フィルター¶
次の例は、リソースコレクションの縮小方法を示しています。 <?php
$manager
// これらの JavaScript はページ下部に配置されます
->collection("jsFooter")
// 最終的に出力されるファイル名
->setTargetPath("final.js")
// このURIで生成されたscriptタグ
->setTargetUri("production/final.js")
// これはフィルタリングを必要としないリモートリソースです
->addJs("code.jquery.com/jquery-1.10.0.min.js", false, false)
// これらはフィルタリングを必要とするローカルリソースです
->addJs("common-functions.js")
->addJs("page-functions.js")
// 全てのリソースを1つのファイルに結合します
->join(true)
// 組み込みの Jsmin フィルターを使います
->addFilter(
new Phalcon\Assets\Filters\Jsmin()
)
// カスタムフィルターを使います
->addFilter(
new MyApp\Assets\Filters\LicenseStamper()
);
コレクションは JavaScript または CSS のリソースを含むことができますが両方はできません。いくつかのリソースはリモートにあるかもしれません、すなわち、それらは更に行われるフィルタリングのためにリモートのソースから HTTP を介して取得されます。取得のオーバーヘッドを排除するため、外部のリソースをローカルに変換することが推奨されています。 前述のように <?php
// これらの JavaScript はページ下部に配置されます
$jsFooterCollection = $manager->collection("jsFooter");
// これはフィルタリングする必要のないリモートのリソースです
$jsFooterCollection->addJs("code.jquery.com/jquery-1.10.0.min.js", false, false);
// これらはフィルタリング必須のローカルリソースです
$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()
);
組み込みのフィルタと自作フィルタ両方がコレクションに対して透過的に適用できることに留意してください。
最後のステップでは、コレクションのすべてのリソースを単一のファイル含めるのか、別々のものに振り分けるのかを決めます。コレクションにすべてのリソースをまとめる指示するには、「 リソースが結合できる場合、リソースを保存するために使用するファイルと、表示するための URL も定義する必要があります。
これらの設定は <?php
$jsFooterCollection->join(true);
// 最後のファイルパスの名前です
$jsFooterCollection->setTargetPath("public/production/final.js");
// このスクリプトのHTMLタグがこのURIで生成されます
$jsFooterCollection->setTargetUri("production/final.js");
もしリソースをまとめようとしているなら、私たちはリソースを保存するのに使うファイルがどれか、それを表示するのに使うファイルがどれかを定義する必要があります。これらの設定は、 組み込みフィルタ¶Phalcon は、JavaScript と CSS のそれぞれに対して圧縮するための 2 つの組み込みフィルタを提供しています。それらの C 言語によるバックエンドは、このタスクを実行するためのオーバーヘッドを最小限に留めてくれます: カスタムフィルタ¶ビルトインフィルタに加え、開発者は独自のフィルタを作成できます。 YUI 、 Sass 、 Closure などの既存のもっと高度なツールを活用することができます: <?php
use Phalcon\Assets\FilterInterface;
/**
* YUI 圧縮による CSS フィルタ
*
* @param string $contents
* @return string
*/
class CssYUICompressor implements FilterInterface
{
protected $_options;
/**
* CssYUICompressor constructor
*
* @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",
]
)
);
前の例では、 <?php
use Phalcon\Assets\FilterInterface;
/**
* ファイル上部にライセンスメッセージを追加します。
*
* @param string $contents
*
* @return string
*/
class LicenseStamper implements FilterInterface
{
/**
* フィルタリング実行
*
* @param string $contents
* @return string
*/
public function filter($contents)
{
$license = "/* (c) 2015 あなたの名前がここにきます */";
return $license . PHP_EOL . PHP_EOL . $contents;
}
}
カスタム出力¶必要な HTML コードを生成する <?php
use Phalcon\Tag;
$jsCollection = $this->assets->collection("js");
foreach ($jsCollection as $resource) {
echo Tag::javascriptInclude(
$resource->getPath()
);
}
Volt: テンプレートエンジン¶Volt は、PHPのためにCで記述されており、とても速く、デザイナにも扱いやすいテンプレート言語です。簡単にビューを書けるようにヘルパーセットを提供します。Volt は、Phalcon の他のコンポーネントに高度に統合されており、また、あなたのアプリケーションの中でスタンドアロンのコンポーネントとしても利用できます。 ![]() Volt は、 Armin Ronacher. によって作られた Jinja にインスパイアされています。そのため、よく似た既存のテンプレートエンジンと同じ記法を採用しており、それらを使うたくさんの開発者が親しみやすくなっています。Voltの記法と機能は、Phalconを使う開発者が慣れ親しんだ、より多くの要素、もちろんパフォーマンスの点においても強化されています。 はじめに¶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の有効化¶他のテンプレートエンジンと同じように、新しい拡張子や標準的な .phtml の拡張子を用いて、Volt をビューコンポーネントに登録することもできます: <?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;
}
);
// Voltをテンプレートエンジンとして登録する
$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:
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";
}
]
);
基本的な使い方¶ビューは、VoltやPHP、HTMLのコードで構成されます。Voltモードでは、特有のデリミタのセットが使用できます。 下記は、いくつかの基本を示す最小限のテンプレートです: {# 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 を使うことで、コントローラからビューへ変数を渡すことができます。上記の例では、 <?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);
}
}
変数¶オブジェクト変数は、 {{ post.title }} {# for $post->title #}
{{ post['title'] }} {# for $post['title'] #}
フィルタ¶変数は、フォーマットしたり、フィルタを用いて加工することができます。変数にフィルタを適用するには、パイプ演算子 | を使います: {{ post.title|e }}
{{ post.content|striptags }}
{{ name|capitalize|trim }}
以下は、Voltで利用可能な、ビルトインのフィルタのリストです:
例: {# 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') }}
コメント¶コメントも、 {# note: this is a comment
{% set price = 100; %}
#}
制御構文¶Voltは、テンプレートの中で使うための、基本的だがパワフルな制御構文のセットを提供しています: for文 ^^^ シーケンス中のそれぞれのアイテムを繰り返し処理します。以下の例では、「robots」のセットを横断して処理し、彼/彼女らの名前を表示する方法を示しています: <h1>Robots</h1>
<ul>
{% for robot in robots %}
<li>
{{ robot.name|e }}
</li>
{% endfor %}
</ul>
forループは入れ子にすることもできます: <h1>Robots</h1>
{% for robot in robots %}
{% for part in robot.parts %}
Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
{% endfor %}
{% endfor %}
以下のシンタックスを用いることで、PHPにおける要素のキーを得ることができます: {% set numbers = ['one': 1, 'two': 2, 'three': 3] %}
{% for name, value in numbers %}
Name: {{ name }} Value: {{ value }}
{% endfor %}
必要に応じて「if」の評価を設定することができます: {% 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 %}
もし、「for」の中で 「else」を定義した場合は、イテレータの結果が 0回のときに、そこに記述した文が実行されるでしょう: <h1>Robots</h1>
{% for robot in robots %}
Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
{% else %}
There are no robots to show
{% endfor %}
代替えシンタックス: <h1>Robots</h1>
{% for robot in robots %}
Robot: {{ robot.name|e }} Part: {{ part.name|e }} <br />
{% elsefor %}
There are no robots to show
{% endfor %}
ループの制御¶「break」と「continue」文は、ループから抜けたり、現在のブロック内で強制的に次のイテレーションへ移ったりすることができます: {# 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文 ^^ PHPと同じように、「if」文は、条件式が true または false に評価されるかをチェックします: <h1>Cyborg Robots</h1>
<ul>
{% for robot in robots %}
{% if robot.type === "cyborg" %}
<li>{{ robot.name|e }}</li>
{% endif %}
{% endfor %}
</ul>
else 文もサポートされています: <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 %}
ループ・コンテキスト¶A special variable is available inside ‘for’ loops providing you information about
{% 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 %}
変数の割り当て¶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:
式¶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 %}
リテラル¶The following literals are supported:
配列¶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'] }}
Curly braces also can be used to define arrays or hashes: {% set myArray = {'Apple', 'Banana', 'Orange'} %}
{% set myHash = {'first': 1, 'second': 4/2, 'third': '3'} %}
演算子¶You may make calculations in templates using the following operators:
比較演算子¶The following comparison operators are available:
論理演算子¶Logic operators are useful in the “if” expression evaluation to combine multiple tests:
その他の演算子¶Additional operators seen the following operators are available:
The following example shows how to use operators: {% set robots = ['Voltron', 'Astro Boy', 'Terminator', 'C3PO'] %}
{% for index in 0..robots|length %}
{% if robots[index] is defined %}
{{ "Name: " ~ robots[index] }}
{% endif %}
{% endfor %}
テスト¶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:
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 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>' }}
タグヘルパの使用¶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:
ビルトイン関数¶The following built-in functions are available in Volt:
Viewの統合¶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’ 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”:
テンプレートの継承¶With template inheritance you can create base templates that can be extended by others templates allowing to reuse code. A base template define blocks than can be overridden by a child template. Let’s pretend that we have the following base template: {# 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 %}© Copyright 2015, All rights reserved.{% endblock %}
</div>
</body>
</html>
From other template we could extend the base template replacing the blocks: {% 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 %}
Not all blocks must be replaced at a child template, only those that are needed. The final output produced will be the following: <!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">
© Copyright 2015, All rights reserved.
</div>
</body>
</html>
多重継承¶Extended templates can extend other templates. The following example illustrates this: {# main.volt #}
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Template “layout.volt” extends “main.volt” {# layout.volt #}
{% extends "main.volt" %}
{% block content %}
<h1>Table of contents</h1>
{% endblock %}
Finally a view that extends “layout.volt”: {# index.volt #}
{% extends "layout.volt" %}
{% block content %}
{{ super() }}
<ul>
<li>Some option</li>
<li>Some other option</li>
</ul>
{% endblock %}
Rendering “index.volt” produces: <!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>
Note the call to the function As partials, the path set to “extends” is a relative path under the current views directory (i.e. app/views/).
自動エスケープモード¶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の拡張¶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 <?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");
フィルタ¶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:
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()
);
View部品のキャッシュ¶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() }}">
スタンドアロン コンポーネント¶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();
外部情報¶
MVC アプリケーション¶Phalcon では MVC の協調動作の背後にある全ての煩雑な作業は通常 Phalcon\Mvc\Application によって遂行されています。 このコンポーネントは、バックグラウンドで必要となる全ての複雑な処理をカプセル化し、必要とされる全てのコンポーネントを初期化して、それらをプロジェクトに統合し、MVC パターンの望ましい動作を実現します。 シングルまたはマルチモジュールアプリケーション¶このコンポーネントを使用すると、様々な種類の MVC 構造を実行することが出来ます。 シングルモジュール¶シングル MVC アプリケーションは 1 つのモジュールだけで構成されています。名前空間を使用することもできますが不要です。このようなアプリケーションでは、下記のようなファイル構成を持つことになります: 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();
// viewコンポーネントを登録
$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();
}
名前空間を使用する場合、下記のブートストラップファイルを使用できます: <?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;
}
);
// view コンポーネントを登録
$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();
}
マルチモジュール¶マルチモジュールアプリケーションは、1 つ以上のモジュールに同じドキュメントルートを使用します。この場合、以下のようなファイル構成が使用できます: 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)
{
// ディスパッチャを登録
$di->set(
"dispatcher",
function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace("Multiple\\Backend\\Controllers");
return $dispatcher;
}
);
// view コンポーネントを登録
$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();
// モジュールのルーティング設定
// 詳細はルーティングの設定を参照 https://docs.phalconphp.com/ja/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",
]
]
);
try {
// リクエストを処理する
$response = $application->handle();
$response->send();
} catch (\Exception $e) {
echo $e->getMessage();
}
モジュール設定をブートストラップファイルで整えたい場合、無名関数を使用してモジュールを登録することができます: <?php
use Phalcon\Mvc\View;
// viewコンポーネントの初期化
$view = new View();
// viewコンポーネントにオプションを設定
// ...
// インストールしたモジュールを登録
$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() という2つのメソッドを実装しなければなりません。これらは、モジュールが実行される際に Phalcon\Mvc\Application に呼ばれます。 アプリケーション・イベント¶Phalcon\Mvc\Application は、 EventsManager にイベントを送ることができます ( EventsManager がある場合)。イベントは「application」というタイプで発火します。以下のイベントがサポートされています: 以下の例は、リスナーへのこのコンポーネントの追加方法を示しています: <?php
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$eventsManager = new EventsManager();
$application->setEventsManager($eventsManager);
$eventsManager->attach(
"application",
function (Event $event, $application) {
// ...
}
);
外部資料¶ルーティング¶ルーターによって、どのコントローラー又はハンドラーがリクエストを受け付けるべきか結びつけを行う、ルートの定義を行うことができます。ルーターはURIの文字列を解析して、この結びつきを決定します。ルーターには2つのモードがあります。MVCモードとマッチオンリーモードです。前者は、MVCのアプリケーションを扱うのに最適です。 ルーティングの定義¶Phalcon\Mvc\Router は高度なルーティング機能を提供しています。MVCモードでは、ルートを定義して、それらを好きなコントローラー・アクションと結びつけることができます。ルートは、以下のように定義します: <?php
use Phalcon\Mvc\Router;
// ルーターの初期化
$router = new Router();
// ルートの定義
$router->add(
"/admin/users/my-profile",
[
"controller" => "users",
"action" => "profile",
]
);
// 別のルートを定義
$router->add(
"/admin/users/change-password",
[
"controller" => "users",
"action" => "changePassword",
]
);
$router->handle();
add()メソッドは、第1引数にURIのパターン、第2引数にパスをとります。上記コード例では、URIが正確に「/admin/users/my-profile」であるとき、「users」コントローラーの「profile」アクションが実行されます。現在のバージョンのPhalconでは、ルーターはコントローラー・アクションを実行しません。ルーターは情報を収集して、コントローラー・アクションを実行する役割を持つコンポーネント(例: Phalcon\Mvc\Dispatcher )に渡しています。 アプリケーションには多くのパスがありうるため、ルートを1つずつ定義するのは大変です。このような場合、より柔軟なルートを作ることができます。 <?php
use Phalcon\Mvc\Router;
// ルーターの初期化
$router = new Router();
// ルートの定義
$router->add(
"/admin/:controller/a/:action/:params",
[
"controller" => 1,
"action" => 2,
"params" => 3,
]
);
上記コード例では、ワイルドカードを使って多くのURIで有効なルートを作っています。例えば、次のURL(/admin/users/a/delete/dave/301)でアクセスすると、コントローラーとパラメーターは以下の表のようになります。
add()メソッドは、定義済みのプレースホルダーや、正規表現の修飾子をパターンとして受け取ることもできます。全てのルーティングパターンは、スラッシュ(/)から始まらなければなりません。正規表現のシンタックスは、 PCRE regular expressions と同じです。正規表現のデリミタを付ける必要は無い点に注意してください。また、全てのルートパターンは、文字の大小を区別します。 第2引数は、マッチした部分がどのようにコントローラー・アクション・パラメーターと結び付けられるかを定義します。マッチする部分には、プレースホルダーと、括弧(丸括弧)によって区切られたサブパターンとがあります。前述したコード例では、最初のサブパターン(:controller)がルートのコントローラーの部分で、2番めがアクション、という具合になっています。 プレースホルダーは、読みやすく理解しやすい正規表現を書く助けになります。以下のプレースホルダーがサポートされています:
コントローラーの名前はキャメルケースに変換されます。ハイフン(-)とアンダースコア(_)は取り除かれ、次の文字が大文字になります。例えば、 some_controller は SomeController に変換されます。 add() メソッドを使うことで好きなだけルートを追加することができるため、ルートが追加された順番が関連性を示します。後で追加されたルートの方が優先して適用されます。内部的には、全ての定義済みルートは、追加された順番とは逆順にマッチングが行われ、 Phalcon\Mvc\Router が与えられたURIに適合するルートを見つけると、残りは無視されます。 名前付きパラメータ¶以下の例では、ルートパラメーターの名前を定義する方法を示しています: <?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” と “show” )に置き換えられています。リクエストによってどのコントローラーに実際に処理が割り当てられるかは、ユーザーにはわかりません。コントローラーの内部では、名前付きパラメーターに以下のようにしてアクセスできます: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function showAction()
{
// "year" のパラメーターを返す
$year = $this->dispatcher->getParam("year");
// "month" のパラメーターを返す
$month = $this->dispatcher->getParam("month");
// "day" のパラメーターを返す
$day = $this->dispatcher->getParam("day");
// ...
}
}
パラメーターの値は、ディスパッチャから取得する点に注意してください。なぜこのようになっているかというと、ディスパッチャがアプリケーションのドライバと最後にやりとりするコンポーネントだからです。さらに、名前付きパラメーターを作成する方法がもう一つあります: <?php
$router->add(
"/documentation/{chapter}/{name}.{type:[a-z]+}",
[
"controller" => "documentation",
"action" => "show",
]
);
これらの値には、前述したのと同じ方法でアクセスできます: <?php
use Phalcon\Mvc\Controller;
class DocumentationController extends Controller
{
public function showAction()
{
// "name" のパラメーターを返す
$name = $this->dispatcher->getParam("name");
// "type" のパラメーターを返す
$type = $this->dispatcher->getParam("type");
// ...
}
}
短縮記法¶ルートパスを定義するのに配列を使いたくない場合、別の記法も利用できます。以下の例は、いずれの書き方でも同じ結果になります: <?php
// 短い書き方
$router->add(
"/posts/{year:[0-9]+}/{title:[a-z\-]+}",
"Posts::show"
);
// 配列を使う書き方
$router->add(
"/posts/([0-9]+)/([a-z\-]+)",
[
"controller" => "posts",
"action" => "show",
"year" => 1,
"title" => 2,
]
);
配列と短縮記法の混合¶配列と短縮記法を混ぜてルートを定義することもできます。この場合、名前付きパラメーターは、それが定義された順番に合わせて自動的にルートのパスに追加されることに注意してください: <?php
// 'country' という名前付きパラメーターが使用されているため
// 1番目のパラメーターは使用してはならない
$router->add(
"/news/{country:[a-z]{2}}/([a-z+])/([a-z\-+])",
[
"section" => 2, // 連番は2から始める
"article" => 3,
]
);
モジュールへのルーティング¶モジュールを含んだルートを定義することができます。これは、複数モジュール構成のアプリケーションに、特に適しています。モジュールのワイルドカードを含んだデフォルトルートを定義することもできます: <?php
use Phalcon\Mvc\Router;
$router = new Router(false);
$router->add(
"/:module/:controller/:action/:params",
[
"module" => 1,
"controller" => 2,
"action" => 3,
"params" => 4,
]
);
この場合、ルートは必ずURLの一部にモジュール名を含まなければなりません。例えば、 /admin/users/edit/sonny のようなURLです。これは、以下のように処理されます:
あるいは、特定のルートに特定のモジュールを紐付けることもできます: <?php
$router->add(
"/login",
[
"module" => "backend",
"controller" => "login",
"action" => "index",
]
);
$router->add(
"/products/:action",
[
"module" => "frontend",
"controller" => "products",
"action" => 1,
]
);
また、特定の名前空間に紐付けることもできます: <?php
$router->add(
"/:namespace/login",
[
"namespace" => 1,
"controller" => "login",
"action" => "index",
]
);
名前空間とクラス名は、別々に渡す必要があります: <?php
$router->add(
"/login",
[
"namespace" => "Backend\\Controllers",
"controller" => "login",
"action" => "index",
]
);
HTTP メソッドの制限¶単に add() を使ってルートを追加した場合、ルートは全てのHTTPメソッドで有効になります。ルートを特定のメソッドだけに制限することも可能で、RESTful APIを持つアプリケーションを作る際には特に便利です: <?php
// HTTPメソッドがGETの場合にだけマッチ
$router->addGet(
"/products/edit/{id}",
"Products::edit"
);
// HTTPメソッドがPOSTの場合だけマッチ
$router->addPost(
"/products/save",
"Products::save"
);
// HTTPメソッドがPOST又はPUTの場合にだけマッチ
$router->add(
"/products/update",
"Products::update"
)->via(
[
"POST",
"PUT",
]
);
convertの使用¶convertメソッドを使うことで、ルートパラメーターを、ディスパッチャに渡される前に自由に変換することができます。以下の例で使い方を示します: <?php
// アクションの名前にはダッシュが許可されているので、アクションは次のようになる: /products/new-ipod-nano-4-generation
$route = $router->add(
"/products/{slug:[a-z\-]+}",
[
"controller" => "products",
"action" => "show",
]
);
$route->convert(
"slug",
function ($slug) {
// ダッシュを取り除く
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);
}
);
ルートのグループ¶ルートのセットが共通のパスを持っている場合、グループ化してメンテナンスを簡単にすることができます: <?php
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
$router = new Router();
// 共通のモジュールとコントローラーのグループを作る
$blog = new RouterGroup(
[
"module" => "blog",
"controller" => "index",
]
);
// /blog から始まる全てのルート
$blog->setPrefix("/blog");
// ルートをグループに追加する
$blog->add(
"/save",
[
"action" => "save",
]
);
// もう一つルートをグループに追加する
$blog->add(
"/edit/{id}",
[
"action" => "edit",
]
);
// このルートはデフォルトとは異なるルートにマッピングする
$blog->add(
"/blog",
[
"controller" => "blog",
"action" => "index",
]
);
// グループをルーターに追加
$router->mount($blog);
ルートのグループを別のファイルに分割して、アプリケーションの構造化とコードの再利用をしやすくする: <?php
use Phalcon\Mvc\Router\Group as RouterGroup;
class BlogRoutes extends RouterGroup
{
public function initialize()
{
// デフォルトパス
$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",
]
);
}
}
ルーターにグループをマウントする <?php
// Add the group to the router
$router->mount(
new BlogRoutes()
);
ルートのマッチ¶ルートが与えられたURIにマッチするかチェックするため、有効なURIがルーターに渡されなければなりません。デフォルトでは、ルーティングURIは、サーバのリライトエンジンモジュールが作成する RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
以下は、ルーターコンポーネントを単独で使用する方法です: <?php
use Phalcon\Mvc\Router;
// ルーターオブジェクトを作る
$router = new Router();
// ルートを何か定義する
// ...
// $_GET["_url"] からURIを取得
$router->handle();
// あるいは、URIの値を直接セットする
$router->handle("/employees/edit/17");
// マッチしたコントローラー名を取得
echo $router->getControllerName();
// マッチしたアクション名を取得
echo $router->getActionName();
// マッチしたルートを取得
$route = $router->getMatchedRoute();
名前付きルート¶ルーターに追加された個々のルートは、 Phalcon\Mvc\Router\Route オブジェクトとして内部に保持されます。このクラスは、それぞれのルートの詳細をカプセル化します。たとえば、パスに名前を付けて、アプリケーション内で一意に識別可能なようにできます。これは、ルートを元にURLを作りたいときには特に便利です。 <?php
$route = $router->add(
"/posts/{year}/{title}",
"Posts::show"
);
$route->setName("show-posts");
次に、例えば Phalcon\Mvc\Url コンポーネントを使って、名前からルートを組み立てることができます: <?php
// /posts/2012/phalcon-1-0-released を返す
echo $url->get(
[
"for" => "show-posts",
"year" => "2012",
"title" => "phalcon-1-0-released",
]
);
使用例¶以下は、カスタマイズしたルートの使用例です: <?php
// "/system/admin/a/edit/7001" にマッチ
$router->add(
"/system/:controller/a/:action/:params",
[
"controller" => 1,
"action" => 2,
"params" => 3,
]
);
// "/es/news" にマッチ
$router->add(
"/([a-z]{2})/:controller",
[
"controller" => 2,
"action" => "index",
"language" => 1,
]
);
// "/es/news" にマッチ
$router->add(
"/{language:[a-z]{2}}/:controller",
[
"controller" => 2,
"action" => "index",
]
);
// "/admin/posts/edit/100" にマッチ
$router->add(
"/admin/:controller/:action/:int",
[
"controller" => 1,
"action" => 2,
"id" => 3,
]
);
// "/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,
]
);
// "/manual/en/translate.adapter.html" にマッチ
$router->add(
"/manual/([a-z]{2})/([a-z\.]+)\.html",
[
"controller" => "manual",
"action" => "show",
"language" => 1,
"file" => 2,
]
);
// /feed/fr/le-robots-hot-news.atom にマッチ
$router->add(
"/feed/{lang:[a-z]+}/{blog:[a-z\-]+}\.{type:[a-z\-]+}",
"Feed::get"
);
// /api/v1/users/peter.json にマッチ
$router->add(
"/api/(v1|v2)/{method:[a-z]+}/{param:[a-z]+}\.(json|xml)",
[
"controller" => "api",
"version" => 1,
"format" => 4,
]
);
デフォルトの振る舞い¶Phalcon\Mvc\Router には、とてもシンプルなルーティングを提供するデフォルトの振る舞いがあります。これは、次のパターンのURIにマッチします: /:controller/:action/:params たとえば、 http://phalconphp.com/documentation/show/about.html のようなURLは、以下のように解釈されます:
このルートをアプリケーションのデフォルトとして使用したくない場合は、ルータを作る際にfalseを渡す必要があります: <?php
use Phalcon\Mvc\Router;
// デフォルトルートなしのルーターを作る
$router = new Router(false);
デフォルトルートを設定する¶アプリケーションがルート無しでアクセスされた場合、’/’ ルートが使われ、サイト・アプリケーションの最初のページが決まります: <?php
$router->add(
"/",
[
"controller" => "index",
"action" => "index",
]
);
Not Found パス¶ルーターの中のどのルートにもマッチしなかった場合に使用される、パスのグループを定義することができます: <?php
// 404のパスをセット
$router->notFound(
[
"controller" => "index",
"action" => "route404",
]
);
デフォルトパスの設定¶モジュール、コントローラー、アクションといった共通のパスのデフォルトを定義することができます。ルートがいずれのパスにもマッチしない場合、デフォルトの値がルーターによって自動的に使用されます: <?php
// デフォルト設定
$router->setDefaultModule("backend");
$router->setDefaultNamespace("Backend\\Controllers");
$router->setDefaultController("index");
$router->setDefaultAction("index");
// 配列の使用
$router->setDefaults(
[
"controller" => "index",
"action" => "index",
]
);
余分なスラッシュの扱い¶ルートの末尾に余分なスラッシュを付けてアクセスされることがあります。余分なスラッシュがあると、ルートにマッチせずディスパッチャーの中でNot Foundの状態になります。ルートの末尾のスラッシュを自動的に取り除くよう、ルーターを設定することができます: <?php
use Phalcon\Mvc\Router;
$router = new Router();
// 末尾のスラッシュを自動的に取り除く
$router->removeExtraSlashes(true);
あるいは、特定のルートだけ選んで、末尾のスラッシュを受け入れるように変更することもできます: <?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",
]
);
マッチングのコールバック¶ルートが特定の条件に合致しなければならない場合、 ‘beforeMatch’ コールバックを使うことで、任意の条件をルートに追加することができます。この関数が false を返すと、ルートがマッチしなかったという扱いになります: <?php
$route = $router->add("/login",
[
"module" => "admin",
"controller" => "session",
]
);
$route->beforeMatch(
function ($uri, $route) {
// リクエストがAjaxによって生成されたかチェック
if (isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest") {
return false;
}
return true;
}
);
追加条件は、クラスにすることで再利用できます: <?php
class AjaxFilter
{
public function check()
{
return $_SERVER["HTTP_X_REQUESTED_WITH"] === "XMLHttpRequest";
}
}
そして、無名関数の代わりに、このクラスを使います: <?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();
}
);
ホスト名によるアクセス制限¶ルーターには、ホスト名による制約を付けることもできます。これは、特定のルートや、ルートのグループに対して、ホスト名の制約にマッチした場合にのみに制限することができる、ということです: <?php
$route = $router->add(
"/login",
[
"module" => "admin",
"controller" => "session",
"action" => "login",
]
);
$route->setHostName("admin.company.com");
ホスト名は正規表現にすることもできます: <?php
$route = $router->add(
"/login",
[
"module" => "admin",
"controller" => "session",
"action" => "login",
]
);
$route->setHostName("([a-z]+).company.com");
ルートのグループの中で、グループの全てのルートに適用されるホスト名の制限を設定することもできます: <?php
use Phalcon\Mvc\Router\Group as RouterGroup;
// Create a group with a common module and controller
$blog = new RouterGroup(
[
"module" => "blog",
"controller" => "posts",
]
);
// ホスト名制限
$blog->setHostName("blog.mycompany.com");
// All the routes start with /blog
$blog->setPrefix("/blog");
// デフォルトルート
$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の情報は <?php
use Phalcon\Mvc\Router;
// ...
// $_GET["_url"] を使う(デフォルト)
$router->setUriSource(
Router::URI_SOURCE_GET_URL
);
// $_SERVER["REQUEST_URI"] を使う
$router->setUriSource(
Router::URI_SOURCE_SERVER_REQUEST_URI
);
あるいは、自分で ‘handle’ メソッドにURIを渡すこともできます: <?php
$router->handle("/some/route/to/handle");
ルートのテスト¶このコンポーネントには依存が無いので、以下のようなファイルを作成してルートのテストをすることができます: <?php
use Phalcon\Mvc\Router;
// これらのルートによって、実際のURIをシミュレートする
$testRoutes = [
"/",
"/index",
"/index/index",
"/index/test",
"/products",
"/products/index/",
"/products/show/101",
];
$router = new Router();
// ここで独自のルートを追加
// ...
// それぞれのルートをテスト
foreach ($testRoutes as $testRoute) {
// ルートの処理
$router->handle($testRoute);
echo "Testing ", $testRoute, "<br>";
// ルートがマッチしたかチェック
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 サービスと統合されたルーティングの定義方法も提供します。この方法を使用することで、サービスに登録することなく、ルートを直接コントローラーに書くことができます: <?php
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;
$di["router"] = function () {
// アノテーションルーターを使う
$router = new RouterAnnotations(false);
// URIが /api/products から始まるときは、 ProductsController からアノテーションを読み取る
$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)
{
}
}
有効なアノテーションでマーキングされたメソッドだけが、ルートとして使われます。サポートされているアノテーションのリストは以下です:
ルートを追加するアノテーションのため、以下のパラメーターがサポートされています:
ルートがモジュール内のコントローラーにマッピングされる場合、 addModuleResource メソッドを使うと良いでしょう: <?php
use Phalcon\Mvc\Router\Annotations as RouterAnnotations;
$di["router"] = function () {
// Use the annotations router
$router = new RouterAnnotations(false);
// URIが /api/products から始まる場合、 Backend\Controllers\ProductsController からアノテーションを読み取る
$router->addModuleResource("backend", "Products", "/api/products");
return $router;
};
ルーターインスタンスの登録¶PhalconのDIコンテナへのサービス登録の際、ルーターを登録することで、ルーターをコントローラーの中で利用できるようになります。以下のコードをブートストラップファイル (例: index.php 、又は Phalcon Developer Tools を使っている場合 app/config/services.php) に追加する必要があります。 <?php
/**
* Add routing capabilities
*/
$di->set(
"router",
function () {
require __DIR__ . "/../app/config/routes.php";
return $router;
}
);
app/config/routes.php を作って、以下のような初期化コードを追加します: <?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;
独自ルータの実装¶独自ルーターを作ってPhalconのルーターを置き換える場合、 Phalcon\Mvc\RouterInterface インターフェイスを実装する必要があります。 Dispatching Controllers¶Phalcon\Mvc\Dispatcher is the component responsible for instantiating controllers and executing the required actions on them in an MVC application. Understanding its operation and capabilities helps us get more out of the services provided by the framework. The Dispatch Loop¶This is an important process that has much to do with the MVC flow itself, especially with the controller part. The work occurs within the controller dispatcher. The controller files are read, loaded, and instantiated. Then the required actions are executed. If an action forwards the flow to another controller/action, the controller dispatcher starts again. To better illustrate this, the following example shows approximately the process performed within Phalcon\Mvc\Dispatcher: <?php
// Dispatch loop
while (!$finished) {
$finished = true;
$controllerClass = $controllerName . "Controller";
// Instantiating the controller class via autoloaders
$controller = new $controllerClass();
// Execute the action
call_user_func_array(
[
$controller,
$actionName . "Action"
],
$params
);
// '$finished' should be reloaded to check if the flow was forwarded to another controller
$finished = true;
}
The code above lacks validations, filters and additional checks, but it demonstrates the normal flow of operation in the dispatcher. Dispatch Loop Events¶Phalcon\Mvc\Dispatcher is able to send events to an EventsManager if it is present. Events are triggered using the type “dispatch”. Some events when returning boolean false could stop the active operation. The following events are supported: The INVO tutorial shows how to take advantage of dispatching events implementing a security filter with Acl The following example demonstrates how to attach listeners to this component: <?php
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an event manager
$eventsManager = new EventsManager();
// Attach a listener for type "dispatch"
$eventsManager->attach(
"dispatch",
function (Event $event, $dispatcher) {
// ...
}
);
$dispatcher = new MvcDispatcher();
// Bind the eventsManager to the view component
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
},
true
);
An instantiated controller automatically acts as a listener for dispatch events, so you can implement methods as callbacks: <?php
use Phalcon\Mvc\Controller;
use Phalcon\Mvc\Dispatcher;
class PostsController extends Controller
{
public function beforeExecuteRoute(Dispatcher $dispatcher)
{
// Executed before every found action
}
public function afterExecuteRoute(Dispatcher $dispatcher)
{
// Executed after every found action
}
}
注釈 Methods on event listeners accept an Phalcon\Events\Event object as their first parameter - methods in controllers do not. 他のアクションへのフォワード¶The dispatch loop allows us to forward the execution flow to another controller/action. This is very useful to check if the user can access to certain options, redirect users to other screens or simply reuse code. <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function saveAction($year, $postTitle)
{
// ... Store some product and forward the user
// Forward flow to the index action
$this->dispatcher->forward(
[
"controller" => "posts",
"action" => "index",
]
);
}
}
Keep in mind that making a “forward” is not the same as making a HTTP redirect. Although they apparently got the same result. The “forward” doesn’t reload the current page, all the redirection occurs in a single request, while the HTTP redirect needs two requests to complete the process. More forwarding examples: <?php
// Forward flow to another action in the current controller
$this->dispatcher->forward(
[
"action" => "search"
]
);
// Forward flow to another action in the current controller
// passing parameters
$this->dispatcher->forward(
[
"action" => "search",
"params" => [1, 2, 3]
]
);
A forward action accepts the following parameters:
パラメータの準備¶Thanks to the hooks points provided by Phalcon\Mvc\Dispatcher you can easily adapt your application to any URL schema: For example, you want your URLs look like: http://example.com/controller/key1/value1/key2/value Parameters by default are passed as they come in the URL to actions, you can transform them to the desired schema: <?php
use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an EventsManager
$eventsManager = new EventsManager();
// Attach a listener
$eventsManager->attach(
"dispatch:beforeDispatchLoop",
function (Event $event, $dispatcher) {
$params = $dispatcher->getParams();
$keyParams = [];
// Use odd parameters as keys and even as values
foreach ($params as $i => $value) {
if ($i & 1) {
// Previous param
$key = $params[$i - 1];
$keyParams[$key] = $value;
}
}
// Override parameters
$dispatcher->setParams($keyParams);
}
);
$dispatcher = new MvcDispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
If the desired schema is: http://example.com/controller/key1:value1/key2:value, the following code is required: <?php
use Phalcon\Dispatcher;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an EventsManager
$eventsManager = new EventsManager();
// Attach a listener
$eventsManager->attach(
"dispatch:beforeDispatchLoop",
function (Event $event, $dispatcher) {
$params = $dispatcher->getParams();
$keyParams = [];
// Explode each parameter as key,value pairs
foreach ($params as $number => $value) {
$parts = explode(":", $value);
$keyParams[$parts[0]] = $parts[1];
}
// Override parameters
$dispatcher->setParams($keyParams);
}
);
$dispatcher = new MvcDispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
パラメータの取得¶When a route provides named parameters you can receive them in a controller, a view or any other component that extends Phalcon\Di\Injectable. <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
// Get the post's title passed in the URL as parameter
// or prepared in an event
$title = $this->dispatcher->getParam("title");
// Get the post's year passed in the URL as parameter
// or prepared in an event also filtering it
$year = $this->dispatcher->getParam("year", "int");
// ...
}
}
アクションの準備¶You can also define an arbitrary schema for actions before be dispatched. アクション名のキャメルケース化¶If the original URL is: http://example.com/admin/products/show-latest-products, and for example you want to camelize ‘show-latest-products’ to ‘ShowLatestProducts’, the following code is required: <?php
use Phalcon\Text;
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an EventsManager
$eventsManager = new EventsManager();
// Camelize actions
$eventsManager->attach(
"dispatch:beforeDispatchLoop",
function (Event $event, $dispatcher) {
$dispatcher->setActionName(
Text::camelize($dispatcher->getActionName())
);
}
);
$dispatcher = new MvcDispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
レガシーな拡張子の削除¶If the original URL always contains a ‘.php’ extension: http://example.com/admin/products/show-latest-products.php http://example.com/admin/products/index.php You can remove it before dispatch the controller/action combination: <?php
use Phalcon\Mvc\Dispatcher as MvcDispatcher;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
$di->set(
"dispatcher",
function () {
// Create an EventsManager
$eventsManager = new EventsManager();
// Remove extension before dispatch
$eventsManager->attach(
"dispatch:beforeDispatchLoop",
function (Event $event, $dispatcher) {
$action = $dispatcher->getActionName();
// Remove extension
$action = preg_replace("/\.php$/", "", $action);
// Override action
$dispatcher->setActionName($action);
}
);
$dispatcher = new MvcDispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
モデルインスタンスの注入¶In this example, the developer wants to inspect the parameters that an action will receive in order to dynamically inject model instances. The controller looks like: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
/**
* Shows posts
*
* @param \Posts $post
*/
public function showAction(Posts $post)
{
$this->view->post = $post;
}
}
Method ‘showAction’ receives an instance of the model Posts, the developer could inspect this before dispatch the action preparing the parameter accordingly: <?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 () {
// Create an EventsManager
$eventsManager = new EventsManager();
$eventsManager->attach(
"dispatch:beforeDispatchLoop",
function (Event $event, $dispatcher) {
// Possible controller class name
$controllerName = $dispatcher->getControllerClass();
// Possible method name
$actionName = $dispatcher->getActiveMethod();
try {
// Get the reflection for the method to be executed
$reflection = new ReflectionMethod($controllerName, $actionName);
$parameters = $reflection->getParameters();
// Check parameters
foreach ($parameters as $parameter) {
// Get the expected model name
$className = $parameter->getClass()->name;
// Check if the parameter expects a model instance
if (is_subclass_of($className, Model::class)) {
$model = $className::findFirstById($dispatcher->getParams()[0]);
// Override the parameters by the model instance
$dispatcher->setParams([$model]);
}
}
} catch (Exception $e) {
// An exception has occurred, maybe the class or action does not exist?
}
}
);
$dispatcher = new MvcDispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
The above example has been simplified for academic purposes. A developer can improve it to inject any kind of dependency or model in actions before be executed. From 3.1.x onwards the dispatcher also comes with an option to handle this internally for all models passed into a controller action by using Phalcon\Mvc\Model\Binder. use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Binder;
$dispatcher = new Dispatcher();
$dispatcher->setModelBinder(new Binder());
return $dispatcher;
It also introduces a new interface Phalcon\Mvc\Model\Binder\BindableInterface which allows you to define the controllers associated models to allow models 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\Model\Binder\BindableInterface
which will add the use Phalcon\Mvc\Model\Binder\BindableInterface;
use Models\Posts;
class PostsController extends CrudController implements BindableInterface
{
public static function getModelName()
{
return Posts::class;
}
}
By declaring the model associated with the PostsController the binder can check the controller for the 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;
}
}
Not-Found Exceptionのハンドリング¶Using the EventsManager it’s possible to insert a hook point before the dispatcher throws an exception when the controller/action combination wasn’t found: <?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 () {
// Create an EventsManager
$eventsManager = new EventsManager();
// Attach a listener
$eventsManager->attach(
"dispatch:beforeException",
function (Event $event, $dispatcher, Exception $exception) {
// Handle 404 exceptions
if ($exception instanceof DispatchException) {
$dispatcher->forward(
[
"controller" => "index",
"action" => "show404",
]
);
return false;
}
// Alternative way, controller or action doesn't exist
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();
// Bind the EventsManager to the dispatcher
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
}
);
Of course, this method can be moved onto independent plugin classes, allowing more than one class take actions when an exception is produced in the dispatch loop: <?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";
// Handle 404 exceptions
if ($exception instanceof DispatchException) {
$action = "show404";
}
$dispatcher->forward(
[
"controller" => "index",
"action" => $action,
]
);
return false;
}
}
独自のディスパッチャの実装¶The Phalcon\Mvc\DispatcherInterface interface must be implemented to create your own dispatcher replacing the one provided by 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();
マイクロアプリケーションの作成¶Phalcon\Mvc\Micro は、マイクロアプリケーションを実装するためのクラスです。 <?php
use Phalcon\Mvc\Micro;
$app = new Micro();
ルーティングの設定¶オブジェクトのインスタンスを作成したら、いくつかのルーティングを設定する必要があります。 Phalcon\Mvc\Router は、ルーティングを管理します。 ルートは、常に/から開始しなければいけません。ルートを設定する際に、HTTPメソッドを任意に制限することができます。 指定したHTTPメソッドに一致したリクエストがあった場合にのみ、正しくルーティングされます。 以下の例では、GETメソッドのルーティングの設定方法を表記しています。 <?php
$app->get(
"/say/hello/{name}",
function ($name) {
echo "<h1>Hello! $name</h1>";
}
);
“get”メソッドは、HTTPメソッドのGETであることを指しています。 <?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 <?php
// Matches if the HTTP method is POST
$app->post(
"/api/products/add",
function () use ($app) {
echo $app->request->getPost("productID");
}
);
パラメータ付きのルーティング¶パラメータ付きのルートは、上記の例のように簡単に設定できます。パラメータ名は括弧で括る必要があります。 パラメータのフォーマットは正規表現を使用して設定できます。 <?php
// This route have two parameters and each of them have a format
$app->get(
"/posts/{year:[0-9]+}/{title:[a-zA-Z\-]+}",
function ($year, $title) {
echo "<h1>Title: $title</h1>";
echo "<h2>Year: $year</h2>";
}
);
トップルート¶通常、アプリケーションのトップルートは、/となり、ほとんどの場合、GETメソッドにてアクセスされると思います。 <?php
// This is the start route
$app->get(
"/",
function () {
echo "<h1>Welcome!</h1>";
}
);
Rewriteルール¶URisのrewriteは、以下のようにApacheで制限します。 <IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^((?s).*)$ index.php?_url=/$1 [QSA,L]
</IfModule>
レスポンス¶ハンドラーの中では自由にレスポンスを設定できます。直接出力したり、テンプレートエンジンを使用したり、ビューをインクルードしたり、JSONを返したり、など。 <?php
// Direct output
$app->get(
"/say/hello",
function () {
echo "<h1>Hello! $name</h1>";
}
);
// Requiring another file
$app->get(
"/show/results",
function () {
require "views/results.php";
}
);
// Returning JSON
$app->get(
"/get/some-json",
function () {
echo json_encode(
[
"some",
"important",
"data",
]
);
}
);
レスポンスについての詳細は、“response” を参照してください。 <?php
$app->get(
"/show/data",
function () use ($app) {
// Set the Content-Type header
$app->response->setContentType("text/plain");
$app->response->sendHeaders();
// Print a file
readfile("data.txt");
}
);
レスポンスオブジェクトを作成して、ハンドラーから返す方法もあります。 <?php
$app->get(
"/show/data",
function () {
// Create a response
$response = new Phalcon\Http\Response();
// Set the Content-Type header
$response->setContentType("text/plain");
// Pass the content of a file
$response->setContent(file_get_contents("data.txt"));
// Return the response
return $response;
}
);
リダイレクト¶リダイレクトによって、別のルートへフォワードすることができます。 <?php
// This route makes a redirection to another route
$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生成¶Phalcon\Mvc\Url では、設定したルーティングに基づいてURLを作成できます。 これを使用するためには、ルートに名前を定義する必要があります。 <?php
// Set a route with the name "show-post"
$app->get(
"/blog/{year}/{title}",
function ($year, $title) use ($app) {
// ... Show the post here
}
)->setName("show-post");
// Produce a URL somewhere
$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¶In the micro application, a Phalcon\Di\FactoryDefault services container is created implicitly; additionally you can create outside the application a container to manipulate its services: <?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!");
}
);
The array-syntax is allowed to easily set/get services in the internal services container: <?php
use Phalcon\Mvc\Micro;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlAdapter;
$app = new Micro();
// Setup the database service
$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”ハンドラーが実行されます。 <?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 が使用することができます。 モデルは自動読み込みで行う必要があります。 <?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();
Inject model instances¶By using class Phalcon\Mvc\Model\Binder you can inject model instances into your routes: <?php
$loader = new \Phalcon\Loader();
$loader->registerDirs(
[
__DIR__ . "/models/"
]
)->register();
$app = new \Phalcon\Mvc\Micro();
$app->setModelBinder(new \Phalcon\Mvc\Model\Binder());
$app->get(
"/products/{product:[0-9]+}",
function (Products $product) {
// do anything with $product object
}
);
$app->handle();
マイクロアプリケーション イベント¶Phalcon\Mvc\Micro is able to send events to the EventsManager (if it is present). Events are triggered using the type “micro”. The following events are supported:
In the following example, we explain how to control the application security using events: <?php
use Phalcon\Mvc\Micro;
use Phalcon\Events\Event;
use Phalcon\Events\Manager as EventsManager;
// Create a events manager
$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();
// Return (false) stop the operation
return false;
}
}
);
$app = new Micro();
// Bind the events manager to the app
$app->setEventsManager($eventsManager);
ミドルウェアイベント¶In addition to the events manager, events can be added using the methods ‘before’, ‘after’ and ‘finish’: <?php
$app = new Phalcon\Mvc\Micro();
// Executed before every route is executed
// Return false cancels the route execution
$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) {
// This is executed after the route is executed
echo json_encode($app->getReturnedValue());
}
);
$app->finish(
function () use ($app) {
// This is executed when the request has been served
}
);
You can call the methods several times to add more events of the same type: <?php
$app->finish(
function () use ($app) {
// First 'finish' middleware
}
);
$app->finish(
function () use ($app) {
// Second 'finish' middleware
}
);
Code for middlewares can be reused using separate classes: <?php
use Phalcon\Mvc\Micro\MiddlewareInterface;
/**
* CacheMiddleware
*
* Caches pages to reduce processing
*/
class CacheMiddleware implements MiddlewareInterface
{
public function call($application)
{
$cache = $application["cache"];
$router = $application["router"];
$key = preg_replace("/^[a-zA-Z0-9]/", "", $router->getRewriteUri());
// Check if the request is cached
if ($cache->exists($key)) {
echo $cache->get($key);
return false;
}
return true;
}
}
Then add the instance to the application: <?php
$app->before(
new CacheMiddleware()
);
以下のミドルウェアイベントが利用可能です。
finish | Executed after sending the response. It can be used to perform clean-up | No |
ハンドラでコントローラの使用¶
<?php
use Phalcon\Mvc\Micro\Collection as MicroCollection;
$posts = new MicroCollection();
// Set the main handler. ie. a controller instance
$posts->setHandler(
new PostsController()
);
// Set a common prefix for all routes
$posts->setPrefix("/posts");
// Use the method 'index' in PostsController
$posts->get("/", "index");
// Use the method 'show' in PostsController
$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)
{
// ...
}
}
上記の例では、コントローラーを直接インスタンス生成していますが、コレクションを使用すると遅延ロードすることができます。 つまり、ルートが一致した場合のみ、コントローラーがロードされます。 <?php
$posts->setHandler("PostsController", true);
$posts->setHandler("Blog\Controllers\PostsController", true);
レスポンスのリターン¶ハンドラーは、Phalcon\Http\Response を使用した生のレスポンスを返したり、または、ビューなどのインターフェイスコンポーネントを返したりすると思います。 ハンドラーによってレスポンスが返されるとき、アプリケーションによって自動的にそれが送信されます。 <?php
use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
$app = new Micro();
// Return a response
$app->get(
"/welcome/index",
function () {
$response = new Response();
$response->setStatusCode(401, "Unauthorized");
$response->setContent("Access is not authorized");
return $response;
}
);
ビューのレンダリング¶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;
};
// 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"
]
);
}
);
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 <?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 can be used to avoid class name collisions; this means that if you have two controllers in an application with the same name, a namespace can be used to differentiate them. Namespaces are also useful for creating bundles or modules. フレームワークのセットアップ¶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;
}
);
名前空間内のコントローラ¶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()
{
}
}
名前空間内のモデル¶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";
イベントマネージャ¶The purpose of this component is to intercept the execution of most of the other components of the framework by creating “hook points”. These hook points allow the developer to obtain status information, manipulate data or change the flow of execution during the process of a component. 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”). 使用例¶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",
]
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);
// Send a SQL command to the database server
$connection->query(
"SELECT * FROM products p WHERE p.status = 1"
);
Now every time a query is executed, the SQL statement will be echoed out. The first parameter passed to the lambda function contains contextual information about the event that is running, the second is the source of the event (in this case: the connection itself). A third parameter may also be specified which will contain arbitrary data specific to the event.
Instead of using lambda functions, you can use event listener classes instead. Event listeners also allow you to listen to multiple events. In this example, we will implement the Phalcon\Db\Profiler to detect the SQL statements that are taking longer to execute than expected: <?php
use Phalcon\Db\Profiler;
use Phalcon\Events\Event;
use Phalcon\Logger;
use Phalcon\Logger\Adapter\File;
class MyDbListener
{
protected $_profiler;
protected $_logger;
/**
* Creates the profiler and starts the logging
*/
public function __construct()
{
$this->_profiler = new Profiler();
$this->_logger = new Logger("../apps/logs/db.log");
}
/**
* This is executed if the event triggered is 'beforeQuery'
*/
public function beforeQuery(Event $event, $connection)
{
$this->_profiler->startProfile(
$connection->getSQLStatement()
);
}
/**
* This is executed if the event triggered is '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
// Create a database listener
$dbListener = new MyDbListener();
// Listen all the database events
$eventsManager->attach(
"db",
$dbListener
);
The resulting profile data can be obtained from the listener: <?php
// Send a SQL command to the database server
$connection->execute(
"SELECT * FROM products p WHERE p.status = 1"
);
foreach ($dbListener->getProfiler()->getProfiles() 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";
}
イベントをトリガするコンポーネントの作成¶You can create components in your application that trigger events to an EventsManager. As a consequence, there may exist listeners
that react to these events when generated. In the following example we’re creating a component called “MyComponent”.
This component is EventsManager aware (it implements Phalcon\Events\EventsAwareInterface); when its <?php
use Phalcon\Events\ManagerInterface;
use Phalcon\Events\EventsAwareInterface;
class MyComponent implements EventsAwareInterface
{
protected $_eventsManager;
public function setEventsManager(ManagerInterface $eventsManager)
{
$this->_eventsManager = $eventsManager;
}
public function getEventsManager()
{
return $this->_eventsManager;
}
public function someTask()
{
$this->_eventsManager->fire("my-component:beforeSomeTask", $this);
// Do some task
echo "Here, someTask\n";
$this->_eventsManager->fire("my-component:afterSomeTask", $this);
}
}
Notice that in this example, we’re using the “my-component” event namespace. Now we need to create an event listener for this component: <?php
use Phalcon\Events\Event;
class SomeListener
{
public function beforeSomeTask(Event $event, $myComponent)
{
echo "Here, beforeSomeTask\n";
}
public function afterSomeTask(Event $event, $myComponent)
{
echo "Here, afterSomeTask\n";
}
}
Now let’s make everything work together: <?php
use Phalcon\Events\Manager as EventsManager;
// Create an Events Manager
$eventsManager = new EventsManager();
// Create the MyComponent instance
$myComponent = new MyComponent();
// Bind the eventsManager to the instance
$myComponent->setEventsManager($eventsManager);
// Attach the listener to the EventsManager
$eventsManager->attach(
"my-component",
new SomeListener()
);
// Execute methods in the component
$myComponent->someTask();
As Here, beforeSomeTask
Here, someTask
Here, afterSomeTask
Additional data may also be passed when triggering an event using the third parameter of <?php
$eventsManager->fire("my-component:afterSomeTask", $this, $extraData);
In a listener the third parameter also receives this data: <?php
use Phalcon\Events\Event;
// Receiving the data in the third parameter
$eventsManager->attach(
"my-component",
function (Event $event, $component, $data) {
print_r($data);
}
);
// Receiving the data from the event context
$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¶Many listeners may be added to the same event manager. This means that for the same type of event, many listeners can be notified. The listeners are notified in the order they were registered in the EventsManager. Some events are cancelable, indicating that these may be stopped preventing other listeners from being notified about the event: <?php
use Phalcon\Events\Event;
$eventsManager->attach(
"db",
function (Event $event, $connection) {
// We stop the event if it is cancelable
if ($event->isCancelable()) {
// Stop the event, so other listeners will not be notified about this
$event->stop();
}
// ...
}
);
By default, events are cancelable - even most of the events produced by the framework are cancelables. You can fire a not-cancelable event
by passing <?php
$eventsManager->fire("my-component:afterSomeTask", $this, $extraData, false);
リスナーの優先度¶When attaching listeners you can set a specific priority. With this feature you can attach listeners indicating the order in which they must be called: <?php
$eventsManager->enablePriorities(true);
$eventsManager->attach("db", new DbListener(), 150); // More priority
$eventsManager->attach("db", new DbListener(), 100); // Normal priority
$eventsManager->attach("db", new DbListener(), 50); // Less priority
レスポンスの収集¶The events manager can collect every response returned by every notified listener. This example explains how it works: <?php
use Phalcon\Events\Manager as EventsManager;
$eventsManager = new EventsManager();
// Set up the events manager to collect responses
$eventsManager->collectResponses(true);
// Attach a listener
$eventsManager->attach(
"custom:custom",
function () {
return "first response";
}
);
// Attach a listener
$eventsManager->attach(
"custom:custom",
function () {
return "second response";
}
);
// Fire the event
$eventsManager->fire("custom:custom", null);
// Get all the collected responses
print_r($eventsManager->getResponses());
The above example produces: Array ( [0] => first response [1] => second response )
独自イベントマネージャの実装¶The Phalcon\Events\ManagerInterface interface must be implemented to create your own EventsManager replacing the one provided by Phalcon. 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";
}
}
値の取得¶PHP automatically fills the superglobal arrays Phalcon\Http\Request allows you to access the values stored in the <?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");
コントローラからリクエストへのアクセス¶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 <?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");
}
}
}
ファイルのアップロード¶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 HTTPヘッダの利用¶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();
レスポンスの返却¶Part of the HTTP cycle is returning responses to clients. Phalcon\Http\Response is the Phalcon component designed to achieve this task. HTTP responses are usually composed by headers and body. The following is an example of basic usage: <?php
use Phalcon\Http\Response;
// Getting a response instance
$response = new Response();
// Set status code
$response->setStatusCode(404, "Not Found");
// Set the content of the response
$response->setContent("Sorry, the page doesn't exist");
// Send response to the client
$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¶Headers are an important part of the HTTP response. It contains useful information about the response state like the HTTP status, type of response and much more. You can set headers in the following way: <?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");
リダイレクト¶With Phalcon\Http\Response you can also execute HTTP redirections: <?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: <?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 HTTPキャッシュ¶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:
有効期限の設定¶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. キャッシュコントロール¶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);
Cookie 管理¶Cookies are a very useful way to store small pieces of data on the client’s machine that can be retrieved even if the user closes his/her browser. Phalcon\Http\Response\Cookies acts as a global bag for cookies. Cookies are stored in this bag during the request execution and are sent automatically at the end of the request. 基本的な使い方¶You can set/get cookies by just accessing the ‘cookies’ service in any part of the application where services can be accessed: <?php
use Phalcon\Mvc\Controller;
class SessionController extends Controller
{
public function loginAction()
{
// Check if the cookie has previously set
if ($this->cookies->has("remember-me")) {
// Get the cookie
$rememberMeCookie = $this->cookies->get("remember-me");
// Get the cookie's value
$value = $rememberMeCookie->getValue();
}
}
public function startAction()
{
$this->cookies->set(
"remember-me",
"some value",
time() + 15 * 86400
);
}
public function logoutAction()
{
$rememberMeCookie = $this->cookies->get("remember-me");
// Delete the cookie
$rememberMeCookie->delete();
}
}
クッキーの暗号化、復号化¶By default, cookies are automatically encrypted before being sent to the client and are decrypted when retrieved from the user. This protection prevents unauthorized users to see the cookies’ contents in the client (browser). Despite this protection, sensitive data should not be stored in cookies. You can disable encryption in the following way: <?php
use Phalcon\Http\Response\Cookies;
$di->set(
"cookies",
function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
}
);
If you wish to use encryption, a global key must be set in the ‘crypt’ service: <?php
use Phalcon\Crypt;
$di->set(
"crypt",
function () {
$crypt = new Crypt();
$crypt->setKey('#1dj8$=dp?.ak//j1V$'); // Use your own key!
return $crypt;
}
);
URL とパスを生成する¶Phalcon\Mvc\Url は Phalcon アプリケーションに置いて、URL 生成を担うコンポーネントです。 ルーティングをベースにした、個々の URL を生成する能力があります。 ベース URI の設定¶アプリケーションをインストールしたドキュメントルートのディレクトリの状況に応じて、ベース URI が必要になる場合があります。 例えば、ドキュメントルートが /var/www/htdocs であなたのアプリケーションが /var/www/htdocs/invo にインストールしてある場合、ベース URI は /invo/ になります。 VirtualHost を使っていたり、またはドキュメントルート直下にインストールしている場合、ベース URI は / になります。 Phalcon が検出しているベース URI を確認するため、下記のコードを実行しましょう。 <?php
use Phalcon\Mvc\Url;
$url = new Url();
echo $url->getBaseUri();
Phalcon は、デフォルトでは自動的にベース URI を検出します。 しかしアプリケーションのパフォーマンスを向上させたい場合は、設定を手動で行うことを推奨しています。 <?php
use Phalcon\Mvc\Url;
$url = new Url();
// ベース URI を相対的に設定
$url->setBaseUri("/invo/");
// ベース URI としてフルドメインを指定する
$url->setBaseUri("//my.domain.com/");
// ベース URI としてフルドメインを指定する
$url->setBaseUri("http://my.domain.com/my-app/");
通常、このコンポーネントは DI コンテナ内で登録されなければならないので、下記のように設定することもできます。 <?php
use Phalcon\Mvc\Url;
$di->set(
"url",
function () {
$url = new Url();
$url->setBaseUri("/invo/");
return $url;
}
);
URI の生成¶もし、:doc:`ルーティング <routing>`のデフォルトの振る舞いを使用するならば、 あなたのアプリケーションのルーティングパターンは /:controller/:action/:params にすることができます。 従って、ルータ内部で定義しているあらゆるパターン含め、GET メソッドへ渡す文字列パターンも簡単に作ることができます。 <?php echo $url->get("products/save"); ?>
ベース URI を先頭につける必要が無いことに注意してください。名前をつけたルートであれば、動的に簡単に変更、作成ができます。 例えば、次のようなルートを持っていたとします。 <?php
$router->add(
"/blog/{year}/{month}/{title}",
[
"controller" => "posts",
"action" => "show",
]
)->setName("show-post");
URL は次のような方法で生成することができます。 <?php
// 結果は /blog/2015/01/some-blog-post となります
$url->get(
[
"for" => "show-post",
"year" => "2015",
"month" => "01",
"title" => "some-blog-post",
]
);
mod_rewrite を使用せずに URL を生成する¶mod_rewrite を使用せずに URL を生成する場合も、このコンポーネントを使うことができます。 <?php
use Phalcon\Mvc\Url;
$url = new Url();
// $_GET["_url"] 内の URI を渡す
$url->setBaseUri("/invo/index.php?_url=/");
// 出力結果は /invo/index.php?_url=/products/save となります。
echo $url->get("products/save");
この際、 <?php
use Phalcon\Mvc\Url;
$url = new Url();
// $_GET["_url"] 内の URI を渡す
$url->setBaseUri("/invo/index.php?_url=/");
// $_SERVER["REQUEST_URI"] を使っ、マニュアルでハンドルが必要になります。て URI を渡す
$url->setBaseUri("/invo/index.php/");
この場合、ルーター内で要求した URI をマニュアルで対処する必要があります。 <?php
use Phalcon\Mvc\Router;
$router = new Router();
// ... ルートをマニュアルで定義する
$uri = str_replace($_SERVER["SCRIPT_NAME"], "", $_SERVER["REQUEST_URI"]);
$router->handle($uri);
結果のルートは下記のようになります <?php
// 結果として /invo/index.php/products/save となります。
echo $url->get("products/save");
Volt での URL の生成¶Volt 内部でこのコンポーネントを使って URL を生成するために url という関数を用意しています。 <a href="{{ url("posts/edit/1002") }}">Edit</a>
静的なルートが生成されます。 <link rel="stylesheet" href="{{ static_url("css/style.css") }}" type="text/css" />
静的な URI vs. 動的な URI¶このコンポーネントは、同一アプリケーション内で異なるベース URI を設定することも許されています。 <?php
use Phalcon\Mvc\Url;
$url = new Url();
// 動的 URI
$url->setBaseUri("/");
// 静的リソースは CDN へ
$url->setStaticBaseUri("http://static.mywebsite.com/");
Phalcon\Tag は、このコンポーネントを使った動的・静的 URI の両方を要求します。 独自 URL ジェネレータの実装¶Phalcon が提供している URL ジェネレータの代わりに独自で URL ジェネレータを作成する場合、 Phalcon\Mvc\UrlInterface インターフェースを必ず実装してください。 メッセージのフラッシュ¶Flash messages are used to notify the user about the state of actions he/she made or simply show information to the users. These kinds of messages can be generated using this component. アダプタ¶This component makes use of adapters to define the behavior of the messages after being passed to the Flasher:
使い方¶Usually the Flash Messaging service is requested from the services container. If you’re using Phalcon\Di\FactoryDefault then Phalcon\Flash\Direct is automatically registered as “flash” service and Phalcon\Flash\Session is automatically registered as “flashSession” service. You can also manually register it: <?php
use Phalcon\Flash\Direct as FlashDirect;
use Phalcon\Flash\Session as FlashSession;
// Set up the flash service
$di->set(
"flash",
function () {
return new FlashDirect();
}
);
// Set up the flash session service
$di->set(
"flashSession",
function () {
return new FlashSession();
}
);
This way, you can use it in controllers or views: <?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
$this->flash->success("The post was correctly saved!");
}
}
There are four built-in message types supported: <?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.");
You can also add messages with your own types using the <?php
$this->flash->message("debug", "this is debug message, you don't say");
メッセージの出力¶Messages sent to the flash service are automatically formatted with 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>
As you can see, CSS classes are added automatically to the :code:`<div>`s. These classes allow you to define the graphical presentation of the messages in the browser. The CSS classes can be overridden, for example, if you’re using Twitter Bootstrap, classes can be configured as: <?php
use Phalcon\Flash\Direct as FlashDirect;
// Register the flash service with custom CSS classes
$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;
}
);
Then the messages would be printed as follows: <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¶Depending on the adapter used to send the messages, it could be producing output directly, or be temporarily storing the messages in session to be shown later. When should you use each? That usually depends on the type of redirection you do after sending the messages. For example, if you make a “forward” is not necessary to store the messages in session, but if you do a HTTP redirect then, they need to be stored in session: <?php
use Phalcon\Mvc\Controller;
class ContactController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
// Store the post
// Using direct flash
$this->flash->success("Your information was stored correctly!");
// Forward to the index action
return $this->dispatcher->forward(
[
"action" => "index"
]
);
}
}
Or using a HTTP redirection: <?php
use Phalcon\Mvc\Controller;
class ContactController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
// Store the post
// Using session flash
$this->flashSession->success("Your information was stored correctly!");
// Make a full HTTP redirection
return $this->response->redirect("contact/index");
}
}
In this case you need to manually print the messages in the corresponding view: <!-- app/views/contact/index.phtml -->
<p><?php $this->flashSession->output() ?></p>
The attribute ‘flashSession’ is how the flash was previously set into the dependency injection container. You need to start the session first to successfully use the flashSession messenger. セッションへのデータの保存¶The session component provides object-oriented wrappers to access session data. Reasons to use this component instead of raw-sessions:
セッションの開始¶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;
}
);
セッションへのデータの保存と取得¶From a controller, a view or any other component that extends Phalcon\Di\Injectable you can access the session service and store items and retrieve them in the following way: <?php
use Phalcon\Mvc\Controller;
class UserController extends Controller
{
public function indexAction()
{
// Set a session variable
$this->session->set("user-name", "Michael");
}
public function welcomeAction()
{
// Check if the variable is defined
if ($this->session->has("user-name")) {
// Retrieve its value
$name = $this->session->get("user-name");
}
}
}
セッションデータの削除と破棄¶It’s also possible remove specific variables or destroy the whole session: <?php
use Phalcon\Mvc\Controller;
class UserController extends Controller
{
public function removeAction()
{
// Remove a session variable
$this->session->remove("user-name");
}
public function logoutAction()
{
// Destroy the whole session
$this->session->destroy();
}
}
アプリケーション毎に別のセッションを使う¶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. セッション・バッグ¶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;
コンポーネントでの永続的なデータ¶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 ( 独自アダプタの実装¶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 フィルタリングとサニタイジング¶Sanitizing user input is a critical part of software development. Trusting or neglecting to sanitize user input could lead to unauthorized access to the content of your application, mainly user data, or even the server your application is hosted on. ![]() The Phalcon\Filter component provides a set of commonly used filters and data sanitizing helpers. It provides object-oriented wrappers around the PHP filter extension. ビルトイン・フィルタの種類¶The following are the built-in filters provided by this component:
データのサニタイズ¶Sanitizing is the process which removes specific characters from a value, that are not required or desired by the user or application. By sanitizing input we ensure that application integrity will be intact. <?php
use Phalcon\Filter;
$filter = new Filter();
// Returns "someone@example.com"
$filter->sanitize("some(one)@exa\mple.com", "email");
// Returns "hello"
$filter->sanitize("hello<<", "string");
// Returns "100019"
$filter->sanitize("!100a019", "int");
// Returns "100019.01"
$filter->sanitize("!100a019.01a", "float");
コントローラでのサニタイジング¶You can access a Phalcon\Filter object from your controllers when accessing GET or POST input data (through the request object). The first parameter is the name of the variable to be obtained; the second is the filter to be applied on it. <?php
use Phalcon\Mvc\Controller;
class ProductsController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
// Sanitizing price from input
$price = $this->request->getPost("price", "double");
// Sanitizing email from input
$email = $this->request->getPost("customerEmail", "email");
}
}
アクションパラメータのフィルタリング¶The next example shows you how to sanitize the action parameters within a controller action: <?php
use Phalcon\Mvc\Controller;
class ProductsController extends Controller
{
public function indexAction()
{
}
public function showAction($productId)
{
$productId = $this->filter->sanitize($productId, "int");
}
}
データのフィルタリング¶In addition to sanitizing, Phalcon\Filter also provides filtering by removing or modifying input data to the format we expect. <?php
use Phalcon\Filter;
$filter = new Filter();
// Returns "Hello"
$filter->sanitize("<h1>Hello</h1>", "striptags");
// Returns "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();
// Returns "Hello"
$filter->sanitize(
" <h1> Hello </h1> ",
[
"striptags",
"trim",
]
);
独自フィルタの作成¶You can add your own filters to Phalcon\Filter. The filter function could be an anonymous function: <?php
use Phalcon\Filter;
$filter = new Filter();
// Using an anonymous function
$filter->add(
"md5",
function ($value) {
return preg_replace("/[^0-9a-f]/", "", $value);
}
);
// Sanitize with the "md5" filter
$filtered = $filter->sanitize($possibleMd5, "md5");
Or, if you prefer, you can implement the filter in a class: <?php
use Phalcon\Filter;
class IPv4Filter
{
public function filter($value)
{
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
}
$filter = new Filter();
// Using an object
$filter->add(
"ipv4",
new IPv4Filter()
);
// Sanitize with the "ipv4" filter
$filteredIp = $filter->sanitize("127.0.0.1", "ipv4");
複雑なサニタイズとフィルタリング¶PHP itself provides an excellent filter extension you can use. Check out its documentation: Data Filtering at PHP Documentation 独自フィルタの実装¶The Phalcon\FilterInterface interface must be implemented to create your own filtering service replacing the one provided by Phalcon. コンテキストのエスケープ¶Websites and web applications are vulnerable to XSS attacks and although PHP provides escaping functionality, in some contexts it is not sufficient/appropriate. Phalcon\Escaper provides contextual escaping and is written in Zephir, providing the minimal overhead when escaping different kinds of texts. We designed this component based on the XSS (Cross Site Scripting) Prevention Cheat Sheet created by the OWASP. Additionally, this component relies on mbstring to support almost any charset. To illustrate how this component works and why it is important, consider the following example: <?php
use Phalcon\Escaper;
// Document title with malicious extra HTML tags
$maliciousTitle = "</title><script>alert(1)</script>";
// Malicious CSS class name
$className = ";`(";
// Malicious CSS font name
$fontName = "Verdana\"</style>";
// Malicious Javascript text
$javascriptText = "';</script>Hello";
// Create an escaper
$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>
Which produces the following: <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
</title><script>alert(1)</script>
</title>
<style type="text/css">
.\3c \2f style\3e {
font-family: "Verdana\22 \3c \2f style\3e";
color: red;
}
</style>
</head>
<body>
<div class='< / style> '>
hello
</div>
<script>
var some = '\x27\x3b\x3c\2fscript\x3eHello';
</script>
</body>
</html>
Every text was escaped according to its context. Use the appropriate context is important to avoid XSS attacks. HTMLのエスケープ¶The most common situation when inserting unsafe data is between HTML tags: <div class="comments">
<!-- Escape untrusted data here! -->
</div>
You can escape those data using the <div class="comments">
<?php echo $e->escapeHtml('></div><h1>myattack</h1>'); ?>
</div>
Which produces: <div class="comments">
></div><h1>myattack</h1>
</div>
HTML属性のエスケープ¶Escaping HTML attributes is different from escaping HTML content. The escaper works by changing every non-alphanumeric character to the form. This kind of escaping is intended to most simpler attributes excluding complex ones like ‘href’ or ‘url’: <table width="Escape untrusted data here!">
<tr>
<td>
Hello
</td>
</tr>
</table>
You can escape a HTML attribute by using the <table width="<?php echo $e->escapeHtmlAttr('"><h1>Hello</table'); ?>">
<tr>
<td>
Hello
</td>
</tr>
</table>
Which produces: <table width=""><h1>Hello</table">
<tr>
<td>
Hello
</td>
</tr>
</table>
URLのエスケープ¶Some HTML attributes like ‘href’ or ‘url’ need to be escaped differently: <a href="Escape untrusted data here!">
Some link
</a>
You can escape a HTML attribute by using the <a href="<?php echo $e->escapeUrl('"><script>alert(1)</script><a href="#'); ?>">
Some link
</a>
Which produces: <a href="%22%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E%3Ca%20href%3D%22%23">
Some link
</a>
CSSのエスケープ¶CSS identifiers/values can be escaped too: <a style="color: Escape untrusted data here">
Some link
</a>
You can escape a CSS identifiers/value by using the <a style="color: <?php echo $e->escapeCss('"><script>alert(1)</script><a href="#'); ?>">
Some link
</a>
Which produces: <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のエスケープ¶Strings to be inserted into JavaScript code also must be properly escaped: <script>
document.title = 'Escape untrusted data here';
</script>
You can escape JavaScript code by using the <script>
document.title = '<?php echo $e->escapeJs("'; alert(100); var x='"); ?>';
</script>
<script>
document.title = '\x27; alert(100); var x\x3d\x27';
</script>
バリデーション¶Phalcon\Validation は任意のデータセットを検証する、独立バリデーションコンポーネントです。 このコンポーネントは、モデルまたはコレクションに属していないデータオブジェクトの検証ルールを実装するために使用することができます。 次の例は基本的な使い方です。 <?php
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email;
use Phalcon\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
"name",
new PresenceOf(
[
"message" => "The name is required",
]
)
);
$validation->add(
"email",
new PresenceOf(
[
"message" => "The e-mail is required",
]
)
);
$validation->add(
"email",
new Email(
[
"message" => "The e-mail is not valid",
]
)
);
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, "<br>";
}
}
このコンポーネントの疎結合な設計思想は、フレームワークによって提供されているバリデータを使って、あなたが自分自身のバリデータを作ることを可能にしています。 バリデーションの初期化¶バリデーションチェーンは Phalcon\Validation オブジェクトにバリデータを追加するという直接的な方法で初期化することができます。 You can put your validations in a separate file for better re-use code and organization: <?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>";
}
}
ビルトイン バリデータ一覧¶Phalcon exposes a set of built-in validators for this component: The following example explains how to create additional validators for this component: <?php
use Phalcon\Validation;
use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;
class IpValidator extends Validator
{
/**
* Executes the validation
*
* @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;
}
}
It is important that validators return a valid boolean value indicating if the validation was successful or not. Callback Validator¶By using Phalcon\Validation\Validator\Callback you can execute custom
function which must return boolean or new validator class which will be used to validate the same field. By returning <?php
use \Phalcon\Validation;
use \Phalcon\Validation\Validator\Callback;
use \Phalcon\Validation\Validator\PresenceOf;
$validation = new Validation();
$validation->add(
"amount",
new Callback(
[
"callback" => function($data) {
return $data["amount"] % 2 == 0;
},
"message" => "Only even number of products are accepted"
]
)
);
$validation->add(
"amount",
new Callback(
[
"callback" => function($data) {
if($data["amount"] % 2 == 0) {
return $data["amount"] != 2;
}
return true;
},
"message" => "You can't buy 2 products"
]
)
);
$validation->add(
"description",
new Callback(
[
"callback" => function($data) {
if($data["amount"] >= 10) {
return new PresenceOf(
[
"message" => "You must write why you need so big amount."
]
);
}
return true;
}
]
)
);
$messages = $validation->validate(["amount" => 1]); // will return message from first validator
$messages = $validation->validate(["amount" => 2]); // will return message from second validator
$messages = $validation->validate(["amount" => 10]); // will return message from validator returned by third validator
バリデーションメッセージ¶Phalcon\Validation has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the validation processes. Each message consists of an instance of the class Phalcon\Validation\Message. The set of
messages generated can be retrieved with the <?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";
}
}
You can pass a ‘message’ parameter to change/translate the default message in each validator: <?php
use Phalcon\Validation\Validator\Email;
$validation->add(
"email",
new Email(
[
"message" => "The e-mail is not valid",
]
)
);
By default, the <?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;
}
}
データのフィルタリング¶Data can be filtered prior to the validation ensuring that malicious or incorrect data is not validated. <?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");
Filtering and sanitizing is performed using the filter component. You can add more filters to this component or use the built-in ones. バリデーション・イベント¶When validations are organized in classes, you can implement the <?php
use Phalcon\Validation;
class LoginValidation extends Validation
{
public function initialize()
{
// ...
}
/**
* Executed before validation
*
* @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;
}
/**
* Executed after validation
*
* @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
}
}
バリデーションのキャンセル¶By default all validators assigned to a field are tested regardless if one of them have failed or not. You can change this behavior by telling the validation component which validator may stop the validation: <?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,
]
)
);
The first validator has the option ‘cancelOnFail’ with a value of true, therefore if that validator fails the remaining validators in the chain are not executed. If you are creating custom validators you can dynamically stop the validation chain by setting the ‘cancelOnFail’ option: <?php
use Phalcon\Validation;
use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;
class MyValidator extends Validator
{
/**
* Executes the validation
*
* @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") {
$this->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 <?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
);
}
}
フォーム¶
The following example shows its basic usage: <?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",
]
)
);
Forms can be rendered based on the form definition: <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>
Each element in the form can be rendered as required by the developer. Internally,
Phalcon\Tag is used to produce the correct HTML for each element and you can pass additional HTML attributes as the second parameter of <p>
<label>
Name
</label>
<?php echo $form->render("name", ["maxlength" => 30, "placeholder" => "Type your name"]); ?>
</p>
HTML attributes also can be set in the element’s definition: <?php
$form->add(
new Text(
"name",
[
"maxlength" => 30,
"placeholder" => "Type your name",
]
)
);
フォームの初期化¶As seen before, forms can be initialized outside the form class by adding elements to it. You can re-use code or organize your form classes implementing the form in a separated file: <?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 extends Phalcon\Di\Injectable so you have access to the application services if needed: <?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"
)
);
}
}
The associated entity added to the form in the initialization and custom user options are passed to the form constructor: <?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"
)
);
}
}
In the form’s instantiation you must use: <?php
$form = new UsersForm(
new Users(),
[
"edit" => true,
]
);
バリデーション¶Phalcon forms are integrated with the validation component to offer instant validation. Built-in or custom validators could be set to each element: <?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);
Then you can validate the form according to the input entered by the user: <?php
if (!$form->isValid($_POST)) {
$messages = $form->getMessages();
foreach ($messages as $message) {
echo $message, "<br>";
}
}
Validators are executed in the same order as they were registered. By default messages generated by all the elements in the form are joined so they can be traversed using a single foreach, you can change this behavior to get the messages separated by the field: <?php
foreach ($form->getMessages(false) as $attribute => $messages) {
echo "Messages generated by ", $attribute, ":", "\n";
foreach ($messages as $message) {
echo $message, "<br>";
}
}
Or get specific messages for an element: <?php
$messages = $form->getMessagesFor("name");
foreach ($messages as $message) {
echo $message, "<br>";
}
フィルタリング¶A form is also able to filter data before it is validated. You can set filters in each element: <?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);
Forms + Entities¶An entity such as a model/collection/plain instance or just a plain PHP class can be linked to the form in order to set default values in the form’s elements or assign the values from the form to the entity easily: <?php
$robot = Robots::findFirst();
$form = new Form($robot);
$form->add(
new Text(
"name"
)
);
$form->add(
new Text(
"year"
)
);
Once the form is rendered if there is no default values assigned to the elements it will use the ones provided by the entity: <?php echo $form->render("name"); ?>
You can validate the form and assign the values from the user input in the following way: <?php
$form->bind($_POST, $robot);
// Check if the form is valid
if ($form->isValid()) {
// Save the entity
$robot->save();
}
Setting up a plain class as entity also is possible: <?php
class Preferences
{
public $timezone = "Europe/Amsterdam";
public $receiveEmails = "No";
}
Using this class as entity, allows the form to take the default values from it: <?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",
]
)
);
Entities can implement getters, which have a higher precedence than public properties. These methods give you more freedom to produce values: <?php
class Preferences
{
public $timezone;
public $receiveEmails;
public function getTimezone()
{
return "Europe/Amsterdam";
}
public function getReceiveEmails()
{
return "No";
}
}
フォーム要素¶Phalcon provides a set of built-in elements to use in your forms, all these elements are located in the Phalcon\Forms\Element namespace:
イベント・コールバック¶Whenever forms are implemented as classes, the callbacks: <?php
use Phalcon\Forms\Form;
class ContactForm extends Form
{
public function beforeValidation()
{
}
}
フォームのレンダリング¶You can render the form with total flexibility, the following example shows how to render each element using a standard procedure: <?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>
Or reuse the logic in your form class: <?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>";
}
}
In the view: <?php
echo $element->renderDecorated("name");
echo $element->renderDecorated("telephone");
フォーム要素の作成¶In addition to the form elements provided by Phalcon you can create your own custom elements: <?php
use Phalcon\Forms\Element;
class MyElement extends Element
{
public function render($attributes = null)
{
$html = // ... Produce some HTML
return $html;
}
}
Forms Manager¶This component provides a forms manager that can be used by the developer to register forms and access them via the service locator: <?php
use Phalcon\Forms\Manager as FormsManager;
$di["forms"] = function () {
return new FormsManager();
};
Forms are added to the forms manager and referenced by a unique name: <?php
$this->forms->set(
"login",
new LoginForm()
);
Using the unique name, forms can be accessed in any part of the application: <?php
$loginForm = $this->forms->get("login");
echo $loginForm->render();
設定の読み込み¶Phalcon\Config は、アプリケーション内で使用する様々なフォーマットの設定ファイルを PHP オブジェクトに変換する際に使用するコンポーネントです。 配列¶最初の例はネイティブの配列をどのように 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);
ファイル アダプタ¶有効なアダプタは下記の通りです: INI ファイルの読み込み¶INI ファイルは設定を保存するための、よくある方法の一つです。Phalcon\Config はこれらのファイルを読む際、最適化された PHP の関数 [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";
設定のマージ¶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 <https://github.com/phalcon/incubator> にはこのコンポーネントのために利用できる複数のアダプタがあります。 構造の依存性を注入する¶Phalcon\Mvc\Controller の内部で Phalcon\Config を使用することで、コントローラに構造の依存性を注入することができます。実現するには設定を呼びたいスクリプト内で次のようなコードを仕込みます。 <?php
use Phalcon\Di\FactoryDefault;
use Phalcon\Config;
// DI の作成
$di = new FactoryDefault();
$di->set(
"config",
function () {
$configData = require "config/config.php";
return new Config($configData);
}
);
これで、次のコードのように config という名前を使って、コントローラ内から設定にアクセスできます: <?php
use Phalcon\Mvc\Controller;
class MyController extends Controller
{
private function getDatabaseName()
{
return $this->config->database->dbname;
}
}
ページネーション¶The process of pagination takes place when we need to present big groups of arbitrary data gradually. データ・アダプタ¶This component makes use of adapters to encapsulate different sources of data:
例¶In the example below, the paginator will use the result of a query from a model as its source data, and limit the displayed data to 10 records per page: <?php
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
// Current page to show
// In a controller/component this can be:
// $this->request->getQuery("page", "int"); // GET
// $this->request->getPost("page", "int"); // POST
$currentPage = (int) $_GET["page"];
// The data set to paginate
$robots = Robots::find();
// Create a Model paginator, show 10 rows by page starting from $currentPage
$paginator = new PaginatorModel(
[
"data" => $robots,
"limit" => 10,
"page" => $currentPage,
]
);
// Get the paginated results
$page = $paginator->getPaginate();
The <table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
<?php foreach ($page->items as $item) { ?>
<tr>
<td><?php echo $item->id; ?></td>
<td><?php echo $item->name; ?></td>
<td><?php echo $item->type; ?></td>
</tr>
<?php } ?>
</table>
The <a href="/robots/search">First</a>
<a href="/robots/search?page=<?= $page->before; ?>">Previous</a>
<a href="/robots/search?page=<?= $page->next; ?>">Next</a>
<a href="/robots/search?page=<?= $page->last; ?>">Last</a>
<?php echo "You are in page ", $page->current, " of ", $page->total_pages; ?>
アダプタの使用方法¶An example of the source data that must be used for each adapter: <?php
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Paginator\Adapter\NativeArray as PaginatorArray;
use Phalcon\Paginator\Adapter\QueryBuilder as PaginatorQueryBuilder;
// Passing a resultset as data
$paginator = new PaginatorModel(
[
"data" => Products::find(),
"limit" => 10,
"page" => $currentPage,
]
);
// Passing an array as data
$paginator = new PaginatorArray(
[
"data" => [
["id" => 1, "name" => "Artichoke"],
["id" => 2, "name" => "Carrots"],
["id" => 3, "name" => "Beet"],
["id" => 4, "name" => "Lettuce"],
["id" => 5, "name" => ""],
],
"limit" => 2,
"page" => $currentPage,
]
);
// Passing a QueryBuilder as data
$builder = $this->modelsManager->createBuilder()
->columns("id, name")
->from("Robots")
->orderBy("name");
$paginator = new PaginatorQueryBuilder(
[
"builder" => $builder,
"limit" => 20,
"page" => 1,
]
);
Pageオブジェクトの持つ属性¶The
独自アダプタの実装¶The Phalcon\Paginator\AdapterInterface interface must be implemented in order to create your own paginator adapters or extend the existing ones: <?php
use Phalcon\Paginator\AdapterInterface as PaginatorInterface;
class MyPaginator implements PaginatorInterface
{
/**
* Adapter constructor
*
* @param array $config
*/
public function __construct($config);
/**
* Set the current page number
*
* @param int $page
*/
public function setCurrentPage($page);
/**
* Returns a slice of the resultset to show in the pagination
*
* @return stdClass
*/
public function getPaginate();
}
キャッシュによるパフォーマンス改善¶Phalcon provides the Phalcon\Cache class allowing faster access to frequently used or already processed data. Phalcon\Cache is written in C, achieving higher performance and reducing the overhead when getting items from the backends. This class uses an internal structure of frontend and backend components. Front-end components act as input sources or interfaces, while backend components offer storage options to the class. どのような時にキャッシュを実装する?¶Although this component is very fast, implementing it in cases that are not needed could lead to a loss of performance rather than gain. We recommend you check this cases before using a cache:
キャッシュの振る舞い¶The caching process is divided into 2 parts:
出力する部品のキャッシュ¶An output fragment is a piece of HTML or text that is cached as is and returned as is. The output is automatically captured from the ob_* functions or the PHP output so that it can be saved in the cache. The following example demonstrates such usage. It receives the output generated by PHP and stores it into a file. The contents of the file are refreshed every 172800 seconds (2 days). The implementation of this caching mechanism allows us to gain performance by not executing the helper <?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;
}
NOTE In the example above, our code remains the same, echoing output to the user as it has been doing before. Our cache component transparently captures that output and stores it in the cache file (when the cache is generated) or it sends it back to the user pre-compiled from a previous call, thus avoiding expensive operations. 任意のデータのキャッシュ¶Caching just data is equally important for your application. Caching can reduce database load by reusing commonly used (but not updated) data, thus speeding up your application. ファイルをバックエンドとする例¶One of the caching adapters is ‘File’. The only key area for this adapter is the location of where the cache files will be stored. This is controlled by the cacheDir option which must have a backslash at the end of it. <?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 をバックエンドとする例¶The above example changes slightly (especially in terms of configuration) when we are using a Memcached backend. <?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";
}
キャッシュの参照¶The elements added to the cache are uniquely identified by a key. In the case of the File backend, the key is the actual filename. To retrieve data from the cache, we just have to call it using the unique key. If the key does not exist, the get method will return null. <?php
// Retrieve products by key "myProducts"
$products = $cache->get("myProducts");
If you want to know which keys are stored in the cache you could call the queryKeys method: <?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¶There are times where you will need to forcibly invalidate a cache entry (due to an update in the cached data). The only requirement is to know the key that the data have been stored with. <?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);
}
キャッシュが存在するかの確認¶It is possible to check if a cache already exists with a given key: <?php
if ($cache->exists("someKey")) {
echo $cache->get("someKey");
} else {
echo "Cache does not exists!";
}
保存期間¶A “lifetime” is a time in seconds that a cache could live without expire. By default, all the created caches use the lifetime set in the frontend creation. You can set a specific lifetime in the creation or retrieving of the data from the cache: 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);
}
Setting the lifetime when saving: <?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);
}
マルチレベル・キャッシュ¶This feature of the cache component, allows the developer to implement a multi-level cache. This new feature is very useful because you can save the same data in several cache locations with different lifetimes, reading first from the one with the faster adapter and ending with the slowest one until the data expires: <?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);
フロントエンド・アダプタ¶The available frontend adapters that are used as interfaces or input sources to the cache are:
Implementing your own Frontend adapters¶The Phalcon\Cache\FrontendInterface interface must be implemented in order to create your own frontend adapters or extend the existing ones. Backend Adapters¶The backend adapters available to store cache data are:
Implementing your own Backend adapters¶The Phalcon\Cache\BackendInterface interface must be implemented in order to create your own backend adapters or extend the existing ones. ファイル・バックエンド オプション¶This backend will store cached content into files in the local server. The available options for this backend are:
Memcached バックエンド オプション¶This backend will store cached content on a memcached server. The available options for this backend are:
APC バックエンド オプション¶This backend will store cached content on Alternative PHP Cache (APC). The available options for this backend are:
Mongo バックエンド オプション¶This backend will store cached content on a MongoDB server. The available options for this backend are:
XCache バックエンド オプション¶This backend will store cached content on XCache (XCache). The available options for this backend are:
Redis Backend Options¶This backend will store cached content on a Redis server (Redis). The available options for this backend are:
There are more adapters available for this components in the Phalcon Incubator セキュリティ¶This component aids the developer in common security tasks such as password hashing and Cross-Site Request Forgery protection (CSRF). パスワードのハッシュ化¶Storing passwords in plain text is a bad security practice. Anyone with access to the database will immediately have access to all user accounts thus being able to engage in unauthorized activities. To combat that, many applications use the familiar one way hashing methods “md5” and “sha1”. However, hardware evolves each day, and becomes faster, these algorithms are becoming vulnerable to brute force attacks. These attacks are also known as rainbow tables. To solve this problem we can use hash algorithms as bcrypt. Why bcrypt? Thanks to its “Eksblowfish” key setup algorithm we can make the password encryption as “slow” as we want. Slow algorithms make the process to calculate the real password behind a hash extremely difficult if not impossible. This will protect your for a long time from a possible attack using rainbow tables. This component gives you the ability to use this algorithm in a simple way: <?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();
}
}
We saved the password hashed with a default work factor. A higher work factor will make the password less vulnerable as its encryption will be slow. We can check if the password is correct as follows: <?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
}
}
The salt is generated using pseudo-random bytes with the PHP’s function openssl_random_pseudo_bytes so is required to have the openssl extension loaded. クロスサイト・リクエスト・フォージェリ(CSRF)保護¶This is another common attack against web sites and applications. Forms designed to perform tasks such as user registration or adding comments are vulnerable to this attack. The idea is to prevent the form values from being sent outside our application. To fix this, we generate a random nonce (token) in each form, add the token in the session and then validate the token once the form posts data back to our application by comparing the stored token in the session to the one submitted by the form: <?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>
Then in the controller’s action you can check if the CSRF token is valid: <?php
use Phalcon\Mvc\Controller;
class SessionController extends Controller
{
public function loginAction()
{
if ($this->request->isPost()) {
if ($this->security->checkToken()) {
// The token is OK
}
}
}
}
Remember to add a session adapter to your Dependency Injector, otherwise the token check won’t work: <?php
$di->setShared(
"session",
function () {
$session = new \Phalcon\Session\Adapter\Files();
$session->start();
return $session;
}
);
Adding a captcha to the form is also recommended to completely avoid the risks of this attack. コンポーネントのセットアップ¶This component is automatically registered in the services container as ‘security’, you can re-register it to setup its options: <?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);
Encryption/Decryption¶Phalcon provides encryption facilities via the Phalcon\Crypt component. This class offers simple object-oriented wrappers to the openssl PHP’s encryption library. By default, this component provides secure encryption using AES-256-CFB.
基本的な使い方¶This component is designed to provide a very simple usage: <?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);
You can use the same instance to encrypt/decrypt several times: <?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
$texts = [
"my-key" => "This is a secret text",
"other-key" => "This is a very secret",
];
foreach ($texts as $key => $text) {
// Perform the encryption
$encrypted = $crypt->encrypt($text, $key);
// Now decrypt
echo $crypt->decrypt($encrypted, $key);
}
暗号化オプション¶The following options are available to change the encryption behavior:
Example: <?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
// Use blowfish
$crypt->setCipher("bf-cbc");
$key = "le password";
$text = "This is a secret text";
echo $crypt->encrypt($text, $key);
Base64 サポート¶In order for encryption to be properly transmitted (emails) or displayed (browsers) base64 encoding is usually applied to encrypted texts: <?php
use Phalcon\Crypt;
// Create an instance
$crypt = new Crypt();
$key = "le password";
$text = "This is a secret text";
$encrypt = $crypt->encryptBase64($text, $key);
echo $crypt->decryptBase64($encrypt, $key);
暗号化サービスのセットアップ¶You can set up the encryption component in the services container in order to use it from any part of the application: <?php
use Phalcon\Crypt;
$di->set(
"crypt",
function () {
$crypt = new Crypt();
// Set a global encryption key
$crypt->setKey(
"%31.1e$i86e$f!8jz"
);
return $crypt;
},
true
);
Then, for example, in a controller you can use it as follows: <?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)¶Phalcon\Acl はACLだけでなく、それらに付随するアクセス権を簡単かつ軽量に管理する機能を提供します。 Access Control Lists (ACL) は、アプリケーションがリクエストによるその領域や背後にあるオブジェクトへのアクセスを制御することを可能にします。あなたがその概念を十分に理解できるよう、ACLの方法論についての詳細を読むことをお勧めします。 要約すると、ACLsは役割とリソースを持っています。リソースとは、ACLsによって定義されたパーミッションに沿うオブジェクトのことです。役割とはACLメカニズムによって、リソースへのアクセスをリクエストしたり、アクセスが許可されたり拒否されたりするオブジェクトのことです。 ACLの生成¶このコンポーネントはメモリー上で最初に動くように設計されています。これにより、利用したり、リストのすべての面に早くアクセスすることが出来る様になります。 Phalcon\Acl コンストラクターは、コントロールリストに関連する情報を回収するアダプターを第一パラメーターにとります。メモリーアダプターを利用する例が以下の様になります。 <?php
use Phalcon\Acl\Adapter\Memory as AclList;
$acl = new AclList();
デフォルトで、 Phalcon\Acl は、未だ定義されていないリソースに対するアクションにアクセスすることを許可します。アクセスリストのセキュリティレベルを上げるに、デフォルトのアクセスレベルである “deny”を定義できます。 <?php
use Phalcon\Acl;
// デフォルトアクションへのアクセスを拒否
$acl->setDefaultAction(
Acl::DENY
);
ACLにロールの追加¶ロールは、アクセスリストの特定のリソースへのアクセスの可否を決定されるオブジェクトです。一例として、組織の中のグループをロールとして定義してみます。Phalcon\Acl\Role によって、ロールをより構造化された方法で作成できます。リストにロールを追加してみましょう: <?php
use Phalcon\Acl\Role;
// いくつかのロールを作成
$roleAdmins = new Role("Administrators", "Super-User role");
$roleGuests = new Role("Guests");
// ACLに「ゲスト」のロールを追加する
$acl->addRole($roleGuests);
// Phalcon\Acl\Roleを利用せずに"デザイナー"ロールを追加
$acl->addRole("Designers");
ご覧のように、インスタンスを使用せずにロールを直接定義することができます。 リソースの追加¶リソースはアクセスが制御されるオブジェクトです。通常、MVCアプリケーションではリソースはコントローラーを参照します。必須ではないものの、 Phalcon\Acl\Resource を使ってリソースを定義することができます。関連するアクションや操作をリソースに追加しておくことは、ACLに何をコントロールすべきか知らせることができるため重要です。 <?php
use Phalcon\Acl\Resource;
// 「顧客」リソースを定義
$customersResource = new Resource("Customers");
// いくつかのオペレーションとともに"顧客"リソースを追加する
$acl->addResource(
$customersResource,
"search"
);
$acl->addResource(
$customersResource,
[
"create",
"update",
]
);
アクセス制御の定義¶ロールとリソースが定義できました。次に、ACLを定義しましょう。要は、どのロールがどのリソースにアクセスするかの定義です。ここは、非常に重要です。特に、デフォルトのアクセスレベルを「allow」にするか「deny」にするかは、慎重に考えましょう。 <?php
// ロールのリソースへのアクセルレベルを設定する。
$acl->allow("Guests", "Customers", "search");
$acl->allow("Guests", "Customers", "create");
$acl->deny("Guests", "Customers", "update");
ACLの照会¶リストが全て定義できました。これで、ロールがパーミッションを与えられているか否か、照会できるようになります。 <?php
// ロールが操作を行う権限を持っているかチェック
// 0が返る
$acl->isAllowed("Guests", "Customers", "edit");
// 1が返る
$acl->isAllowed("Guests", "Customers", "search");
// 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 <?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 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 Our <?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 <?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 <?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 <?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 ロールの継承¶Phalcon\Acl\Role の提供する継承機能を用いることで、複雑なロールの構造を作ることができます。ロールは別のロールを継承することができ、リソースのスーパーセットやサブセットへのアクセスを許可することができます。ロールの継承を使うには、ロールをリストに追加する際、継承されるロールを第2パラメータに渡す必要があります。 <?php
use Phalcon\Acl\Role;
// ...
// Create some roles
$roleAdmins = new Role("Administrators", "Super-User role");
$roleGuests = new Role("Guests");
// Add "Guests" role to ACL
$acl->addRole($roleGuests);
// 「Administrators」ロールに、「Guests」ロールから継承したアクセス権を与える
$acl->addRole($roleAdmins, $roleGuests);
ACLリストのシリアライズ¶パフォーマンス向上のため、 Phalcon\Acl のインスタンスをシリアライズして、APC、セッション、テキストファイルやデータベースのテーブルに保存しておくことができます。こうすることで、リスト全体の再定義を行うことなく、好きな時にリストを呼び出すことができます。以下のように実装できます: <?php
use Phalcon\Acl\Adapter\Memory as AclList;
// ...
// ACLデータが既に存在するかどうかをチェックする
if (!is_file("app/security/acl.data")) {
$acl = new AclList();
// ロール、リソース、アクセスなどを定義
// シリアライズされたリストをファイルに格納
file_put_contents(
"app/security/acl.data",
serialize($acl)
);
} else {
// シリアライズされたファイルからACLオブジェクトを復元
$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イベント¶Phalcon\Acl は、 EventsManager にイベントを送れます。イベントは”acl”というタイプで発火します。falseを返すイベントは、現在の処理を中断させることがあります。以下のイベントがサポートされています:
以下の例では、リスナーにこのコンポーネントを紐付けています: <?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();
// $acl をセットアップ
// ...
// aclコンポーネントにイベントマネージャーを紐付け
$acl->setEventsManager($eventsManager);
独自アダプタの実装¶Phalcon\Acl\AdapterInterface インターフェースを実装することで、独自のACLアダプタを作成したり、既存のアダプタを継承したりできます。 多言語対応¶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. アダプタ一覧¶This component makes use of adapters to read translation messages from different sources in a unified way.
コンポーネントの使い方¶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 <?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 <!-- welcome -->
<!-- String: hi => 'Hello' -->
<p><?php echo $t->_("hi"), " ", $name; ?></p>
The <!-- 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. 独自アダプタの実装¶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. セキュリティレイヤ¶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. 名前空間の登録¶If you’re organizing your code using namespaces, or using external libraries which do, the <?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 ファイル拡張子の追加¶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",
]
);
現状の振る舞いの変更¶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
);
オートロード時のイベント¶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:
トラブルシューティング¶Some things to keep in mind when using the universal autoloader:
ロギング¶Phalcon\Logger is a component whose purpose is to provide logging services for applications. It offers logging to different backends using different adapters. It also offers transaction logging, configuration options, different formats and filters. You can use the Phalcon\Logger for every logging need your application has, from debugging processes to tracing application flow. アダプタ¶This component makes use of adapters to store the logged messages. The use of adapters allows for a common logging interface which provides the ability to easily switch backends if necessary. The adapters supported are:
ログの作成¶The example below shows how to create a log and add messages to it: <?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"
);
// You can also pass context parameters like this
$logger->log(
"This is a {message}",
[
'message' => 'parameter'
]
);
The log generated is below: [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
[Tue, 28 Jul 15 22:09:02 -0500][DEBUG] This is a parameter
You can also set a log level using the <?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. トランザクション¶Logging data to an adapter i.e. File (file system) is always an expensive operation in terms of performance. To combat that, you can take advantage of logging transactions. Transactions store log data temporarily in memory and later on write the data to the relevant adapter (File in this case) in a single atomic operation. <?php
use Phalcon\Logger\Adapter\File as FileAdapter;
// Create the logger
$logger = new FileAdapter("app/logs/test.log");
// Start a transaction
$logger->begin();
// Add messages
$logger->alert(
"This is an alert"
);
$logger->error(
"This is another error"
);
// Commit messages to file
$logger->commit();
複数のハンドラへのロギング¶Phalcon\Logger can send messages to multiple handlers with a just single call: <?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"
);
The messages are sent to the handlers in the order they were registered. メッセージフォーマット¶This component makes use of ‘formatters’ to format messages before sending them to the backend. The formatters available are:
行フォーマット¶Formats the messages using a one-line string. The default logging format is: [%date%][%type%] %message%
You can change the default format using
The example below shows how to change the log format: <?php
use Phalcon\Logger\Formatter\Line as LineFormatter;
$formatter = new LineFormatter("%date% - %message%");
// Changing the logger format
$logger->setFormatter($formatter);
独自フォーマッタの実装¶The Phalcon\Logger\FormatterInterface interface must be implemented in order to create your own logger formatter or extend the existing ones. アダプタ¶The following examples show the basic use of each adapter: ストリーム ロガー¶The stream logger writes messages to a valid registered stream in PHP. A list of streams is available here: <?php
use Phalcon\Logger\Adapter\Stream as StreamAdapter;
// Opens a stream using zlib compression
$logger = new StreamAdapter("compress.zlib://week.log.gz");
// Writes the logs to stderr
$logger = new StreamAdapter("php://stderr");
ファイル ロガー¶This logger uses plain files to log any kind of data. By default all logger files are opened using append mode which opens the files for writing only; placing the file pointer at the end of the file. If the file does not exist, an attempt will be made to create it. You can change this mode by passing additional options to the constructor: <?php
use Phalcon\Logger\Adapter\File as FileAdapter;
// Create the file logger in 'w' mode
$logger = new FileAdapter(
"app/logs/test.log",
[
"mode" => "w",
]
);
Syslog ロガー¶This logger sends messages to the system logger. The syslog behavior may vary from one operating system to another. <?php
use Phalcon\Logger\Adapter\Syslog as SyslogAdapter;
// Basic Usage
$logger = new SyslogAdapter(null);
// Setting ident/mode/facility
$logger = new SyslogAdapter(
"ident-name",
[
"option" => LOG_NDELAY,
"facility" => LOG_MAIL,
]
);
FirePHP ロガー¶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"
);
独自アダプタの実装¶The Phalcon\Logger\AdapterInterface interface must be implemented in order to create your own logger adapters or extend the existing ones. アノテーション パーサー¶アノテーションのパーサーがCで実装されたのは、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)
*/
アノテーションの読み取り¶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 が使用されています。このアダプタはリクエストの間にだけ、キャッシュを行います。そのため、このアダプタは開発用に適しています。本番環境では、他のアダプタを使ってキャッシュを行うこともできます。 アノテーションの種類¶アノテーションは、パラメータを持つこともあれば持たないこともあります。パラメータには、単純なリテラル(文字列、数値、真偽値、null)、配列、連想配列、別のアノテーション、があります: <?php
/**
* Simple Annotation
*
* @SomeAnnotation
*/
/**
* Annotation with parameters
*
* @SomeAnnotation("hello", "world", 1, 2, 3, false, true)
*/
/**
* Annotation with named parameters
*
* @SomeAnnotation(first="hello", second="world", third=1)
* @SomeAnnotation(first: "hello", second: "world", third: 1)
*/
/**
* Passing an array
*
* @SomeAnnotation([1, 2, 3, 4])
* @SomeAnnotation({1, 2, 3, 4})
*/
/**
* Passing a hash as parameter
*
* @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])
*/
/**
* Nested arrays/hashes
*
* @SomeAnnotation({"name"="SomeName", "other"={
* "foo1": "bar1", "foo2": "bar2", {1, 2, 3},
* }})
*/
/**
* Nested Annotations
*
* @SomeAnnotation(first=@AnotherAnnotation(1, 2, 3))
*/
実用的な使用法¶次に、PHPのアプリケーションでの、アノテーションの実用的な使用例を説明します: アノテーションでのキャッシュの有効化¶以下のコントローラーがあり、開発者は直近に実行されたアクションがキャッシュ可能だとマーキングされた場合は、自動的にキャッシュを開始するプラグインを作成しようとしている、と想定してみましょう。最初に、プラグインをディスパッチャに登録して、ルートの実行を通知されるようにします: <?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はディスパッチャで実行された全てのアクションに割り込み、必要に応じてキャッシュを有効化します: <?php
use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\User\Plugin;
/**
* Enables the cache for a view if the latest
* executed action has the annotation @Cache
*/
class CacheEnablerPlugin extends Plugin
{
/**
* This event is executed before every route is executed in the 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 = $annotation->getNamedParameter("lifetime");
$options = [
"lifetime" => $lifetime,
];
// ユーザーが定義したキャッシュのキーがあるか確認する
if ($annotation->hasNamedParameter("key")) {
$options["key"] = $annotation->getNamedParameter("key");
}
// 現在のメソッドのキャッシュを有効にする
$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;
}
}
アノテーションアダプタ¶このコンポーネントはアダプタを利用して、パースした処理済みのアノテーションをキャッシュすることができ、パフォーマンスを向上させ開発・テストを便利にします:
独自のアダプタを実装する¶Phalcon\Annotations\AdapterInterface インターフェースを実装することで、独自のアノテーションアダプタを作成したり、既存のものを継承したりできます。 コマンドライン アプリケーション¶CLI アプリケーションはコマンドラインから実行されます。これらは cron ジョブやスクリプト、コマンドユーティリティ等を作成するのに便利です。 構造¶CLI アプリケーションの最小構成はこんな感じになります:
ブートストラップの作成¶通常の MVC アプリケーションのように、ブートストラップファイルはアプリケーションの起動に使用されます。Web アプリケーションではおなじみの index.php の代わりに、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 = new ConsoleApp();
$console->setDI($di);
/**
* コンソールの引数を処理
*/
$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 work similar to controllers. Any CLI application needs at least a MainTask and a mainAction and every task needs to have a mainAction which will run if no action is given explicitly. Below is an example of the app/tasks/MainTask.php file: <?php
use Phalcon\Cli\Task;
class MainTask extends Task
{
public function mainAction()
{
echo "This is the default task and the default action" . PHP_EOL;
}
}
アクションパラメータの処理¶It’s possible to pass parameters to actions, the code for this is already present in the sample bootstrap. If you run the application with the following parameters and 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;
}
}
We can then run the following command: $ php app/cli.php main test world universe
hello world
best regards, universe
Running tasks in a chain¶It’s also possible to run tasks in a chain if it’s required. To accomplish this you must add the console itself to the DI: <?php
$di->setShared("console", $console);
try {
// Handle incoming arguments
$console->handle($arguments);
} catch (\Phalcon\Exception $e) {
echo $e->getMessage();
exit(255);
}
Then you can use the console inside of any task. Below is an example of a modified 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;
$this->console->handle(
[
"task" => "main",
"action" => "test",
]
);
}
public function testAction()
{
echo "I will get printed too!" . PHP_EOL;
}
}
However, it’s a better idea to extend Phalcon\Cli\Task and implement this kind of logic there. Images¶Phalcon\Image is the component that allows you to manipulate image files. Multiple operations can be performed on the same image object.
Adapters¶This component makes use of adapters to encapsulate specific image manipulator programs. The following image manipulator programs are supported:
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:
|
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,
]
);
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.
Phalcon\Db is the component behind Phalcon\Mvc\Model that powers the model layer in the framework. It consists of an independent high-level abstraction layer for database systems completely written in C.
This component allows for a lower level database manipulation than using traditional models.
This guide is not intended to be a complete documentation of available methods and their arguments. Please visit the API for a complete reference.
This component makes use of adapters to encapsulate specific database system details. Phalcon uses PDO to connect to databases. The following database engines are supported:
Class | Description |
---|---|
Phalcon\Db\Adapter\Pdo\Mysql | Is the world’s most used relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases |
Phalcon\Db\Adapter\Pdo\Postgresql | PostgreSQL is a powerful, open source relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. |
Phalcon\Db\Adapter\Pdo\Sqlite | SQLite is a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine |
The Phalcon\Db\AdapterInterface interface must be implemented in order to create your own database adapters or extend the existing ones.
Phalcon encapsulates the specific details of each database engine in dialects. Those provide common functions and SQL generator to the adapters.
Class | Description | |
---|---|---|
Phalcon\Db\Dialect\Mysql | SQL specific dialect for MySQL database system | |
Phalcon\Db\Dialect\Postgresql | SQL specific dialect for PostgreSQL database system | |
Phalcon\Db\Dialect\Sqlite | SQL specific dialect for SQLite database system |
The Phalcon\Db\DialectInterface interface must be implemented in order to create your own database dialects or extend the existing ones.
To create a connection it’s necessary instantiate the adapter class. It only requires an array with the connection parameters. The example below shows how to create a connection passing both required and optional parameters:
<?php
// Required
$config = [
"host" => "127.0.0.1",
"username" => "mike",
"password" => "sigma",
"dbname" => "test_db",
];
// Optional
$config["persistent"] = false;
// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
<?php
// Required
$config = [
"host" => "localhost",
"username" => "postgres",
"password" => "secret1",
"dbname" => "template",
];
// Optional
$config["schema"] = "public";
// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Postgresql($config);
<?php
// Required
$config = [
"dbname" => "/path/to/database.db",
];
// Create a connection
$connection = new \Phalcon\Db\Adapter\Pdo\Sqlite($config);
You can set PDO options at connection time by passing the parameters ‘options’:
<?php
// Create a connection with 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,
]
]
);
Phalcon\Db provides several methods to query rows from tables. The specific SQL syntax of the target database engine is required in this case:
<?php
$sql = "SELECT id, name FROM robots ORDER BY name";
// Send a SQL statement to the database system
$result = $connection->query($sql);
// Print each robot name
while ($robot = $result->fetch()) {
echo $robot["name"];
}
// Get all rows in an array
$robots = $connection->fetchAll($sql);
foreach ($robots as $robot) {
echo $robot["name"];
}
// Get only the first row
$robot = $connection->fetchOne($sql);
By default these calls create arrays with both associative and numeric indexes. You can change this behavior by using Phalcon\Db\Result::setFetchMode()
. This method receives a constant, defining which kind of index is required.
Constant | Description |
---|---|
Phalcon\Db::FETCH_NUM |
Return an array with numeric indexes |
Phalcon\Db::FETCH_ASSOC |
Return an array with associative indexes |
Phalcon\Db::FETCH_BOTH |
Return an array with both associative and numeric indexes |
Phalcon\Db::FETCH_OBJ |
Return an object instead of an array |
<?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];
}
The Phalcon\Db::query()
returns an instance of Phalcon\Db\Result\Pdo. These objects encapsulate all the functionality related to the returned resultset i.e. traversing, seeking specific records, count etc.
<?php
$sql = "SELECT id, name FROM robots";
$result = $connection->query($sql);
// Traverse the resultset
while ($robot = $result->fetch()) {
echo $robot["name"];
}
// Seek to the third row
$result->seek(2);
$robot = $result->fetch();
// Count the resultset
echo $result->numRows();
Bound parameters is also supported in Phalcon\Db. Although there is a minimal performance impact by using bound parameters, you are encouraged to use this methodology so as to eliminate the possibility of your code being subject to SQL injection attacks. Both string and positional placeholders are supported. Binding parameters can simply be achieved as follows:
<?php
// Binding with numeric placeholders
$sql = "SELECT * FROM robots WHERE name = ? ORDER BY name";
$result = $connection->query(
$sql,
[
"Wall-E",
]
);
// Binding with named placeholders
$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",
]
);
To insert, update or delete rows, you can use raw SQL or use the preset functions provided by the class:
<?php
// Inserting data with a raw SQL statement
$sql = "INSERT INTO `robots`(`name`, `year`) VALUES ('Astro Boy', 1952)";
$success = $connection->execute($sql);
// With placeholders
$sql = "INSERT INTO `robots`(`name`, `year`) VALUES (?, ?)";
$success = $connection->execute(
$sql,
[
"Astro Boy",
1952,
]
);
// Generating dynamically the necessary SQL
$success = $connection->insert(
"robots",
[
"Astro Boy",
1952,
],
[
"name",
"year",
],
);
// Generating dynamically the necessary SQL (another syntax)
$success = $connection->insertAsDict(
"robots",
[
"name" => "Astro Boy",
"year" => 1952,
]
);
// Updating data with a raw SQL statement
$sql = "UPDATE `robots` SET `name` = 'Astro boy' WHERE `id` = 101";
$success = $connection->execute($sql);
// With placeholders
$sql = "UPDATE `robots` SET `name` = ? WHERE `id` = ?";
$success = $connection->execute(
$sql,
[
"Astro Boy",
101,
]
);
// Generating dynamically the necessary SQL
$success = $connection->update(
"robots",
[
"name",
],
[
"New Astro Boy",
],
"id = 101" // Warning! In this case values are not escaped
);
// Generating dynamically the necessary SQL (another syntax)
$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
]
);
// Deleting data with a raw SQL statement
$sql = "DELETE `robots` WHERE `id` = 101";
$success = $connection->execute($sql);
// With placeholders
$sql = "DELETE `robots` WHERE `id` = ?";
$success = $connection->execute($sql, [101]);
// Generating dynamically the necessary SQL
$success = $connection->delete(
"robots",
"id = ?",
[
101,
]
);
Working with transactions is supported as it is with PDO. Perform data manipulation inside transactions often increase the performance on most database systems:
<?php
try {
// Start a transaction
$connection->begin();
// Execute some SQL statements
$connection->execute("DELETE `robots` WHERE `id` = 101");
$connection->execute("DELETE `robots` WHERE `id` = 102");
$connection->execute("DELETE `robots` WHERE `id` = 103");
// Commit if everything goes well
$connection->commit();
} catch (Exception $e) {
// An exception has occurred rollback the transaction
$connection->rollback();
}
In addition to standard transactions, Phalcon\Db provides built-in support for nested transactions (if the database system used supports them). When you call begin() for a second time a nested transaction is created:
<?php
try {
// Start a transaction
$connection->begin();
// Execute some SQL statements
$connection->execute("DELETE `robots` WHERE `id` = 101");
try {
// Start a nested transaction
$connection->begin();
// Execute these SQL statements into the nested transaction
$connection->execute("DELETE `robots` WHERE `id` = 102");
$connection->execute("DELETE `robots` WHERE `id` = 103");
// Create a save point
$connection->commit();
} catch (Exception $e) {
// An error has occurred, release the nested transaction
$connection->rollback();
}
// Continue, executing more SQL statements
$connection->execute("DELETE `robots` WHERE `id` = 104");
// Commit if everything goes well
$connection->commit();
} catch (Exception $e) {
// An exception has occurred rollback the transaction
$connection->rollback();
}
Phalcon\Db is able to send events to a EventsManager if it’s present. Some events when returning boolean false could stop the active operation. The following events are supported:
Event Name | Triggered | Can stop operation? |
---|---|---|
afterConnect | After a successfully connection to a database system | No |
beforeQuery | Before send a SQL statement to the database system | Yes |
afterQuery | After send a SQL statement to database system | No |
beforeDisconnect | Before close a temporal database connection | No |
beginTransaction | Before a transaction is going to be started | No |
rollbackTransaction | Before a transaction is rollbacked | No |
commitTransaction | Before a transaction is committed | No |
Bind an EventsManager to a connection is simple, Phalcon\Db will trigger the events with the type “db”:
<?php
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as Connection;
$eventsManager = new EventsManager();
// Listen all the database events
$eventsManager->attach('db', $dbListener);
$connection = new Connection(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);
Stop SQL operations are very useful if for example you want to implement some last-resource SQL injector checker:
<?php
use Phalcon\Events\Event;
$eventsManager->attach(
"db:beforeQuery",
function (Event $event, $connection) {
$sql = $connection->getSQLStatement();
// Check for malicious words in SQL statements
if (preg_match("/DROP|ALTER/i", $sql)) {
// DROP/ALTER operations aren't allowed in the application,
// this must be a SQL injection!
return false;
}
// It's OK
return true;
}
);
Phalcon\Db includes a profiling component called Phalcon\Db\Profiler, that is used to analyze the performance of database operations so as to diagnose performance problems and discover bottlenecks.
Database profiling is really easy With 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();
// Listen all the database events
$eventsManager->attach(
"db",
function (Event $event, $connection) use ($profiler) {
if ($event->getType() === "beforeQuery") {
$sql = $connection->getSQLStatement();
// Start a profile with the active connection
$profiler->startProfile($sql);
}
if ($event->getType() === "afterQuery") {
// Stop the active profile
$profiler->stopProfile();
}
}
);
// Assign the events manager to the connection
$connection->setEventsManager($eventsManager);
$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";
You can also create your own profile class based on Phalcon\Db\Profiler to record real time statistics of the statements sent to the database system:
<?php
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Profiler as Profiler;
use Phalcon\Db\Profiler\Item as Item;
class DbProfiler extends Profiler
{
/**
* Executed before the SQL statement will sent to the db server
*/
public function beforeStartProfile(Item $profile)
{
echo $profile->getSQLStatement();
}
/**
* Executed after the SQL statement was sent to the db server
*/
public function afterEndProfile(Item $profile)
{
echo $profile->getTotalElapsedSeconds();
}
}
// Create an Events Manager
$eventsManager = new EventsManager();
// Create a listener
$dbProfiler = new DbProfiler();
// Attach the listener listening for all database events
$eventsManager->attach("db", $dbProfiler);
Using high-level abstraction components such as Phalcon\Db to access a database, it is difficult to understand which statements are sent to the database system. Phalcon\Logger interacts with Phalcon\Db, providing logging capabilities on the database abstraction layer.
<?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);
}
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);
// Execute some SQL statement
$connection->insert(
"products",
[
"Hot pepper",
3.50,
],
[
"name",
"price",
]
);
As above, the file app/logs/db.log will contain something like this:
[Sun, 29 Apr 12 22:35:26 -0500][DEBUG][Resource Id #77] INSERT INTO products
(name, price) VALUES ('Hot pepper', 3.50)
You can implement your own logger class for database queries, by creating a class that implements a single method called “log”.
The method needs to accept a string as the first argument. You can then pass your logging object to Phalcon\Db::setLogger()
,
and from then on any SQL statement executed will call that method to log the results.
Phalcon\Db also provides methods to retrieve detailed information about tables and views:
<?php
// Get tables on the test_db database
$tables = $connection->listTables("test_db");
// Is there a table 'robots' in the database?
$exists = $connection->tableExists("robots");
// Get name, data types and special features of 'robots' fields
$fields = $connection->describeColumns("robots");
foreach ($fields as $field) {
echo "Column Type: ", $field["Type"];
}
// Get indexes on the 'robots' table
$indexes = $connection->describeIndexes("robots");
foreach ($indexes as $index) {
print_r(
$index->getColumns()
);
}
// Get foreign keys on the 'robots' table
$references = $connection->describeReferences("robots");
foreach ($references as $reference) {
// Print referenced columns
print_r(
$reference->getReferencedColumns()
);
}
A table description is very similar to the MySQL describe command, it contains the following information:
Index | Description |
---|---|
Field | Field’s name |
Type | Column Type |
Key | Is the column part of the primary key or an index? |
Null | Does the column allow null values? |
Methods to get information about views are also implemented for every supported database system:
<?php
// Get views on the test_db database
$tables = $connection->listViews("test_db");
// Is there a view 'robots' in the database?
$exists = $connection->viewExists("robots");
Different database systems (MySQL, Postgresql etc.) offer the ability to create, alter or drop tables with the use of commands such as CREATE, ALTER or DROP. The SQL syntax differs based on which database system is used. Phalcon\Db offers a unified interface to alter tables, without the need to differentiate the SQL syntax based on the target storage system.
The following example shows how to create a table:
<?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()
accepts an associative array describing the table. Columns are defined with the class
Phalcon\Db\Column. The table below shows the options available to define a column:
Option | Description | Optional |
---|---|---|
“type” | Column type. Must be a Phalcon\Db\Column constant (see below for a list) | No |
“primary” | True if the column is part of the table’s primary key | Yes |
“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 many decimals should be stored | 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 |
“default” | Default value (when used with "notNull" => true ). |
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 |
“bind” | One of the BIND_TYPE_* constants telling how the column must be binded before save it | Yes |
“first” | Column must be placed at first position in the column order | Yes |
“after” | Column must be placed after indicated column | Yes |
Phalcon\Db supports the following database column types:
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
The associative array passed in Phalcon\Db::createTable()
can have the possible keys:
Index | Description | Optional |
---|---|---|
“columns” | An array with a set of table columns defined with Phalcon\Db\Column | No |
“indexes” | An array with a set of table indexes defined with Phalcon\Db\Index | Yes |
“references” | An array with a set of table references (foreign keys) defined with Phalcon\Db\Reference | Yes |
“options” | An array with a set of table creation options. These options often relate to the database system in which the migration was generated. | Yes |
As your application grows, you might need to alter your database, as part of a refactoring or adding new features. Not all database systems allow to modify existing columns or add columns between two existing ones. Phalcon\Db is limited by these constraints.
<?php
use Phalcon\Db\Column as Column;
// Adding a new column
$connection->addColumn(
"robots",
null,
new Column(
"robot_type",
[
"type" => Column::TYPE_VARCHAR,
"size" => 32,
"notNull" => true,
"after" => "name",
]
)
);
// Modifying an existing column
$connection->modifyColumn(
"robots",
null,
new Column(
"name",
[
"type" => Column::TYPE_VARCHAR,
"size" => 40,
"notNull" => true,
]
)
);
// Deleting the column "name"
$connection->dropColumn(
"robots",
null,
"name"
);
Examples on dropping tables:
<?php
// Drop table robot from active database
$connection->dropTable("robots");
// Drop table robot from database "machines"
$connection->dropTable("robots", "machines");
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.
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:
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);
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"));
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
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.
The Phalcon Developer Tools provides scripts to manage migrations (generation, running and rollback).
The available options for generating migrations are:
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.
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:
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 |
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 |
“default” | Defines a default value for a column (can only be an actual value, not a function such as NOW()) | 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
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.
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 |
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",
]
);
}
}
Once the generated migrations are uploaded on the target server, you can easily run them as shown in the following example:
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.
PHP offers tools to debug applications with notices, warnings, errors and exceptions. The Exception class offers information such as the file, line, message, numeric code, backtrace etc. on where an error occurred. OOP frameworks like Phalcon mainly use this class to encapsulate this functionality and provide information back to the developer or user.
Despite being written in C, Phalcon executes methods in the PHP userland, providing the debug capability that any other application or framework written in PHP has.
Throughout the tutorials and examples of the Phalcon documentation, there is a common element that is catching exceptions. This is a try/catch block:
<?php
try {
// ... Some Phalcon/PHP code
} catch (\Exception $e) {
}
Any exception thrown within the block is captured in the variable $e
. A Phalcon\Exception extends the
PHP Exception class and is used to understand whether the exception came from Phalcon or PHP itself.
All exceptions generated by PHP are based on the Exception class, and have at least the following elements:
<?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 )
}
Retrieving information from Phalcon\Exception is the same as PHP’s Exception class:
<?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();
}
It’s therefore easy to find which file and line of the application’s code generated the exception, as well as the components involved in generating the exception:
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}
As you can see from the above output the Phalcon’s classes and methods are displayed just like any other component, and even showing the parameters that were invoked in every call. The method Exception::getTrace provides additional information if needed.
Phalcon provides a debug component that allows the developer to easily find errors produced in an application created with the framework.
The following screencast explains how it works:
To enable it, add the following to your bootstrap:
<?php
$debug = new \Phalcon\Debug();
$debug->listen();
Any Try/Catch blocks must be removed or disabled to make this component work properly.
Any instance of a Phalcon class offers exactly the same behavior than a PHP normal one. It’s possible to use the Reflection API or simply print any object to show how is its internal state:
<?php
$router = new Phalcon\Mvc\Router();
print_r($router);
It’s easy to know the internal state of any object. The above example prints the following:
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 is an amazing tool that complements the debugging of PHP applications. It is also a C extension for PHP, and you can use it together with Phalcon without additional configuration or side effects.
The following screencast shows a Xdebug session with Phalcon:
Once you have xdebug installed, you can use its API to get a more detailed information about exceptions and messages.
We highly recommend use at least XDebug 2.2.3 for a better compatibility with Phalcon
The following example implements xdebug_print_function_stack to stop the execution and generate a backtrace:
<?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();
}
}
In this instance, Xdebug will also show us the variables in the local scope, and a backtrace as well:
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 provides several ways to get debug and trace information regarding the execution of your application using Phalcon. You can check the XDebug documentation for more information.
適切なテストを書くことは、より良いソフトウェアを書く助けになります。適切なテストケースを組み立てれば、機能面のバグの多くを削減でき、より良いメンテナンスを行えるようになります。
PHPUnitをまだインストールしていないなら、以下のcomposerコマンドでインストールできます:
composer require phpunit/phpunit:^5.0
あるいは、composer.json に以下の記述を追加します:
{
"require-dev": {
"phpunit/phpunit": "^5.0"
}
}
PHPUnitをインストールしたら、「tests」ディレクトリをルートディレクトリの直下に作成しましょう:
app/
public/
tests/
次に、ユニットテストの前にアプリケーションを立ち上げるための「ヘルパー」ファイルが必要になります。
ヘルパーファイルは、テスト実行のためにアプリケーションを立ち上げます。以下のサンプルファイルを、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()
);
// phalcon/incubator のために必要
include __DIR__ . "/../vendor/autoload.php";
// アプリケーションのオートローダを使用してクラスをオートロードする
// composerの依存関係をオートロードする
$loader = new Loader();
$loader->registerDirs(
[
ROOT_PATH,
]
);
$loader->register();
$di = new FactoryDefault();
Di::reset();
// 必要なサービスをDIに登録する
Di::setDefault($di);
独自ライブラリのコンポーネントをテストするなら、それらをオートローダーに登録するか、アプリケーション本体のオートローダを使用してください。
ユニットテストの作成を助けるため、ユニットテスト自体を立ち上げる抽象クラスを用意しました。これらのファイルは https://github.com/phalcon/incubator にあるPhalcon incubatorの中にあります。
incubatorライブラリを使うには以下のcomposerコマンドで追加します:
composer require phalcon/incubator
あるいは、composer.json に以下の記述を追加します:
{
"require": {
"phalcon/incubator": "^3.0"
}
}
あるいは、リポジトリを上のリンクからgitでcloneすることもできます。
次に、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/ ディレクトリ配下の全てのテストが実行されます。
ユニットテストを実行するには、それらを定義する必要があります。オートローダが必要なファイルを読み込むので、必要なことはテストケースを作成することだけです。そうすれば、PHPUnitがテストを実行してくれます。
この例には設定ファイルが含まれていませんが、多くのテストケースでは設定ファイルの読み込みが必要になります。UnitTestCaseファイルでDIに追加することができます。
はじめに、UnitTestCase.php という名前のユニットテストのベースとなるクラスを、/tests ディレクトリの下に作りましょう:
<?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();
// テスト中に必要になる追加のサービスを読み込み
$di = Di::getDefault();
// ここで必要なDIコンポーネントを取得する。config があるなら、それを 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/
Get faster applications requires refine many aspects: server, client, network, database, web server, static sources, etc. In this chapter we highlight scenarios where you can improve performance and how detect what is really slow in your application.
Each application is different, the permanent profiling is important to understand where performance can be increased. Profiling gives us a real picture on what is really slow and what does not. Profiles can vary between a request and another, so it is important to make enough measurements to make conclusions.
Xdebug provides an easier way to profile PHP applications, just install the extension and enable profiling in the php.ini:
xdebug.profiler_enable = On
Using a tool like Webgrind you can see which functions/methods are slower than others:
Xhprof is another interesting extension to profile PHP applications. Add the following line to the start of the bootstrap file:
<?php
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
Then at the end of the file save the profiled data:
<?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 provides a built-in HTML viewer to analyze the profiled data:
Most database systems provide tools to identify slow SQL statements. Detecting and fixing slow queries is very important in order to increase performance in the server side. In the Mysql case, you can use the slow query log to know what SQL queries are taking more time than expected:
log-slow-queries = /var/log/slow-queries.log
long_query_time = 1.5
Sometimes we may need to improve the loading of static elements such as images, javascript and css to improve performance. The following tools are useful to detect common bottlenecks in the client side:
YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages
Speed Tracer is a tool to help you identify and fix performance problems in your web applications. It visualizes metrics that are taken from low level instrumentation points inside of the browser and analyzes them as your application runs. Speed Tracer is available as a Chrome extension and works on all platforms where extensions are currently supported (Windows and Linux).
This tool is very useful because it help you to get the real time used to render the whole page including HTML parsing, Javascript evaluation and CSS styling.
PHP is faster every day, using the latest version improves the performance of your applications and also of Phalcon.
APC as many other bytecode caches help an application to reduce the overhead of read, tokenize and parse PHP files in each request. Once the extension is installed use the following setting to enable APC:
apc.enabled = On
PHP 5.5 includes a built-in bytecode cache called ZendOptimizer+, this extension is also available for 5.3 and 5.4.
Process a video, send e-mails, compress a file or an image, etc., are slow tasks that must be processed in background jobs. There are a variety of tools that provide queuing or messaging systems that work well with PHP:
mod_pagespeed speeds up your site and reduces page load time. This open-source Apache HTTP server module (also available for nginx as ngx_pagespeed) automatically applies web performance best practices to pages, and associated assets (CSS, JavaScript, images) without requiring that you modify your existing content or workflow.
以下の例は少々長めですが、なぜサービス・ロケーションと依存性の注入を使用するのかを説明しています。初めに、SomeComponentというコンポーネントを開発しているとしましょう。これは、今のところ重要ではないタスクを実行します。このコンポーネントは、DB接続に依存しています。
この最初のサンプルでは、コンポーネントの中でDB接続オブジェクトを作成しています。このアプローチは、実用的ではありません。コンポーネントのDB接続のパラメータを外部から操作したり、DBMSの種類を変更したりといった操作が行えないからです。
<?php
class SomeComponent
{
/**
* The instantiation of the connection is hardcoded inside
* the component, therefore it's difficult replace it externally
* or change its behavior
*/
public function someDbTask()
{
$connection = new Connection(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
// ...
}
}
$some = new SomeComponent();
$some->someDbTask();
この問題を解決するため、依存しているオブジェクトを、使用する前に外部から注入するセッターを作りました。今のところ、これはよい解決法のようにみえます。
<?php
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection)
{
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
// DB接続を作成する
$connection = new Connection(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
// DB接続をコンポーネントに注入する
$some->setConnection($connection);
$some->someDbTask();
ここで、このコンポーネントをアプリケーションの別の部分で使用すると考えると、コンポーネントを使う度にDB接続を作成して渡す必要があるでしょう。ある種のグローバルな容れ物からDB接続を取得できるようにすれば、何度もDB接続を作る必要は無くなるはずです:
<?php
class Registry
{
/**
* Returns the connection
*/
public static function getConnection()
{
return new Connection(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection)
{
$this->_connection = $connection;
}
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
}
$some = new SomeComponent();
// Registry内で定義されたDB接続を渡す
$some->setConnection(Registry::getConnection());
$some->someDbTask();
ここで、コンポーネントに2つのメソッドを実装しなければならないと想像してみましょう。1つは常に新しいDB接続を作成する必要があり、もう1つは共有されたDB接続を必要とします:
<?php
class Registry
{
protected static $_connection;
/**
* Creates a connection
*/
protected static function _createConnection()
{
return new Connection(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
}
/**
* Creates a connection only once and returns it
*/
public static function getSharedConnection()
{
if (self::$_connection === null) {
self::$_connection = self::_createConnection();
}
return self::$_connection;
}
/**
* Always returns a new connection
*/
public static function getNewConnection()
{
return self::_createConnection();
}
}
class SomeComponent
{
protected $_connection;
/**
* Sets the connection externally
*/
public function setConnection($connection)
{
$this->_connection = $connection;
}
/**
* This method always needs the shared connection
*/
public function someDbTask()
{
$connection = $this->_connection;
// ...
}
/**
* This method always needs a new connection
*/
public function someOtherDbTask($connection)
{
}
}
$some = new SomeComponent();
// このメソッドは共有のDB接続を注入する
$some->setConnection(
Registry::getSharedConnection()
);
$some->someDbTask();
// ここでは、新しいDB接続を常にパラメーターとして渡す
$some->someOtherDbTask(
Registry::getNewConnection()
);
ここまで、依存性の注入がいかにして我々の問題を解決するかをみてきました。依存しているオブジェクトを、内部で作成するのではなく、引数として渡せるようにすることで、アプリケーションはよりメンテナンスしやすく、疎結合になります。しかし、長い目で見ると、この形の依存性の注入には欠点があります。
たとえば、もしコンポーネントに多数の依存関係があるなら、依存しているオブジェクトを渡すための多くの引数をもつセッターを作成するか、多くの引数をもつコンストラクタを作成する必要があります。加えて、コンポーネントを使う度に依存しているオブジェクトを全て作成する必要があり、コードのメンテナンス性は失われてしまいます:
<?php
// 依存オブジェクトの作成(あるいは、Registryからの取得)
$connection = new Connection();
$session = new Session();
$fileSystem = new FileSystem();
$filter = new Filter();
$selector = new Selector();
// コンストラクタに渡す
$some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);
// あるいは、セッターを使用する
$some->setConnection($connection);
$some->setSession($session);
$some->setFileSystem($fileSystem);
$some->setFilter($filter);
$some->setSelector($selector);
このオブジェクトをアプリケーションの多くの部分で作成しなければならないと考えてみましょう。もし、依存関係のいずれも必要としないのであれば、このオブジェクトに依存性を注入しているところから、コンストラクタ(あるいはセッター)のパラメーターを取り除く必要があります。この問題を解決するため、コンポーネントを作成するためのグローバルな容れ物、という考え方に立ち戻ってみましょう。ただし、ここではオブジェクトを作る前に抽象化のレイヤーを追加しています:
<?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サービスを取得
// 常に新しいconnectionを返す
$connection = $this->_di->get("db");
}
public function someOtherDbTask()
{
// 共有のconnectionサービスを取得
// 常に同じconnectionサービスを返す
$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();
これで、コンポーネントは必要とするサービスにシンプルにアクセスできるようになりました。不要なサービスは、初期化されることさえないので、リソースを節約できます。コンポーネントは高度に疎結合です。たとえば、コンポーネントの振る舞いやその他の側面を変更せずに、DB接続のやり方を変更することができます。
あなたが 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();
Phalcon\Mvc\Application を使いたくない場合、前述のコードは以下のように変更できます:
<?php
// ルーティングサービスを取得する
$router = $di["router"];
$router->handle();
$view = $di["view"];
$dispatcher = $di["dispatcher"];
// 処理済みのルートパラメータをディスパッチャに渡す
$dispatcher->setControllerName(
$router->getControllerName()
);
$dispatcher->setActionName(
$router->getActionName()
);
$dispatcher->setParams(
$router->getParams()
);
// viewの開始
$view->start();
// リクエストを処理する
$dispatcher->dispatch();
// 関連するビューの描画
$view->render(
$dispatcher->getControllerName(),
$dispatcher->getActionName(),
$dispatcher->getParams()
);
// viewの終了
$view->finish();
$response = $di["response"];
// ビューの出力をレスポンスに渡す
$response->setContent(
$view->getContent()
);
// レスポンスを送信
$response->send();
以下の、 Phalcon\Mvc\Application の代替となるコードは、viewコンポーネントを使用していないため、REST APIに適しています:
<?php
use Phalcon\Http\ResponseInterface;
// ルーティングサービスを取得する
$router = $di["router"];
$router->handle();
$dispatcher = $di["dispatcher"];
// 処理済みのルータパラメータをディスパッチャに渡す
$dispatcher->setControllerName(
$router->getControllerName()
);
$dispatcher->setActionName(
$router->getActionName()
);
$dispatcher->setParams(
$router->getParams()
);
// Dispatch the request
$dispatcher->dispatch();
// 直前に実行されたアクションの返り値を取得
$response = $dispatcher->getReturnedValue();
// 返り値がResponseオブジェクトのインスタンスか確認する
if ($response instanceof ResponseInterface) {
// リクエストを送信する
$response->send();
}
ディスパッチャで生成された例外をキャッチして、別のアクションを実行するやり方の代替が以下になります:
<?php
use Phalcon\Http\ResponseInterface;
// ルーティングサービスを取得する
$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) {
// 例外が発生した場合、それに対応するコントローラーとアクションを実行する
// 処理済みのルータパラメータをディスパッチャに渡す
$dispatcher->setControllerName("errors");
$dispatcher->setActionName("action503");
// リクエストを割り振る
$dispatcher->dispatch();
}
// 最後に実行したアクションによる戻り値を取得する
$response = $dispatcher->getReturnedValue();
// アクションが「レスポンス」オブジェクトかどうか確認する
if ($response instanceof ResponseInterface) {
// レスポンスを送信する
$response->send();
}
上記した実装は Phalcon\Mvc\Application を使用するものよりもずっと多くの情報を含んでいますが、これはアプリケーションの初期化の別のやり方です。場合によって、何がインスタンス化されるかを全てコントロールしたい場合もあるでしょうし、特定のコンポーネントを、基本的な機能を継承した独自コンポーネントで置き換えたい場合もあるでしょう。
implements Phalcon\Acl\AdapterInterface, Phalcon\Events\EventsAwareInterface
Adapter for Phalcon\Acl adapters
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
...
extends abstract class Phalcon\Acl\Adapter
implements Phalcon\Events\EventsAwareInterface, Phalcon\Acl\AdapterInterface
Manages ACL lists in memory
<?php
$acl = new \Phalcon\Acl\Adapter\Memory();
$acl->setDefaultAction(
\Phalcon\Acl::DENY
);
// Register roles
$roles = [
"users" => new \Phalcon\Acl\Role("Users"),
"guests" => new \Phalcon\Acl\Role("Guests"),
];
foreach ($roles as $role) {
$acl->addRole($role);
}
// Private area resources
$privateResources = [
"companies" => ["index", "search", "new", "edit", "save", "create", "delete"],
"products" => ["index", "search", "new", "edit", "save", "create", "delete"],
"invoices" => ["index", "profile"],
];
foreach ($privateResources as $resourceName => $actions) {
$acl->addResource(
new \Phalcon\Acl\Resource($resourceName),
$actions
);
}
// Public area resources
$publicResources = [
"index" => ["index"],
"about" => ["index"],
"session" => ["index", "register", "start", "end"],
"contact" => ["index", "send"],
];
foreach ($publicResources as $resourceName => $actions) {
$acl->addResource(
new \Phalcon\Acl\Resource($resourceName),
$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);
}
}
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"),
[
"create",
"search",
]
);
$acl->addResource(
"customers",
[
"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", ["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", ["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 (RoleInterface | RoleAware | string $roleName, ResourceInterface | ResourceAware | string $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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Acl\ResourceInterface
This class defines resource entity and its description
public getName ()
Resource name
public __toString ()
Resource name
public getDescription ()
Resource description
public __construct (mixed $name, [mixed $description])
Phalcon\Acl\Resource constructor
implements Phalcon\Acl\RoleInterface
This class defines role entity and its description
public getName ()
Role name
public __toString ()
Role name
public getDescription ()
Role description
public __construct (mixed $name, [mixed $description])
Phalcon\Acl\Role constructor
implements Phalcon\Annotations\AdapterInterface
This is the base class for Phalcon\Annotations adapters
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
extends abstract class Phalcon\Annotations\Adapter
implements Phalcon\Annotations\AdapterInterface
Stores the parsed annotations in APC. This adapter is suitable for production
<?php
use Phalcon\Annotations\Adapter\Apc;
$annotations = new Apc();
public __construct ([array $options])
Phalcon\Annotations\Adapter\Apc constructor
public read (mixed $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
extends abstract class Phalcon\Annotations\Adapter
implements Phalcon\Annotations\AdapterInterface
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/",
]
);
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
extends abstract class Phalcon\Annotations\Adapter
implements Phalcon\Annotations\AdapterInterface
Stores the parsed annotations in memory. This adapter is the suitable development/testing
public read (mixed $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
extends abstract class Phalcon\Annotations\Adapter
implements Phalcon\Annotations\AdapterInterface
Stores the parsed annotations to XCache. This adapter is suitable for production
<?php
$annotations = new \Phalcon\Annotations\Adapter\Xcache();
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
Represents a single annotation in an annotations collection
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
implements Iterator, Traversable, Countable
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");
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
extends class Exception
implements Throwable
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
implements Phalcon\Annotations\ReaderInterface
Parses docblocks returning an array with the found annotations
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
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();
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface
Base class for Phalcon\Cli\Console and Phalcon\Mvc\Application.
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
extends class Phalcon\Exception
implements Throwable
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
implements Countable, Iterator, Traversable
Represents a collection of resources
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Assets\FilterInterface
Minify the css - removes comments removes newlines and line feeds keeping removes last semicolon from last property
implements Phalcon\Assets\FilterInterface
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.
implements Phalcon\Assets\FilterInterface
Returns the content without make any modification to the original source
Represents an inline asset
<?php
$inline = new \Phalcon\Assets\Inline("js", "alert('hello world');");
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
extends class Phalcon\Assets\Inline
Represents an inlined CSS
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
extends class Phalcon\Assets\Inline
Represents an inline Javascript
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
Manages collections of CSS/Javascript assets
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
Represents an asset resource
<?php
$resource = new \Phalcon\Assets\Resource("js", "javascripts/jquery.js");
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
extends class Phalcon\Assets\Resource
Represents CSS resources
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
extends class Phalcon\Assets\Resource
Represents Javascript resources
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
implements Phalcon\Cache\BackendInterface
This class implements common functionality for backend adapters. A backend cache adapter may extend this class
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
abstract public get (mixed $keyName, [mixed $lifetime]) inherited from Phalcon\Cache\BackendInterface
...
abstract public save ([mixed $keyName], [mixed $content], [mixed $lifetime], [mixed $stopBuffer]) inherited from Phalcon\Cache\BackendInterface
...
abstract public delete (mixed $keyName) inherited from Phalcon\Cache\BackendInterface
...
abstract public queryKeys ([mixed $prefix]) inherited from Phalcon\Cache\BackendInterface
...
abstract public exists ([mixed $keyName], [mixed $lifetime]) inherited from Phalcon\Cache\BackendInterface
...
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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");
public get (mixed $keyName, [mixed $lifetime])
Returns a cached content
public save ([string | int $keyName], [string $content], [int $lifetime], [boolean $stopBuffer])
Stores cached content into the APC backend and stops the frontend
public increment ([string $keyName], [mixed $value])
Increment of a given key, by number $value
public decrement ([string $keyName], [mixed $value])
Decrement of a given key, by number $value
public delete (mixed $keyName)
Deletes a value from the cache by its key
public queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string | int $keyName], [int $lifetime])
Checks if cache exists and it hasn’t expired
public flush ()
Immediately invalidates all existing items.
<?php
use Phalcon\Cache\Backend\Apc;
$cache = new Apc($frontCache, ["prefix" => "app-data"]);
$cache->save("my-data", [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 __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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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;
}
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 delete (int | string $keyName)
Deletes a value from the cache by its key
public queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string | int $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public increment ([string | int $keyName], [mixed $value])
Increment of a given key, by number $value
public decrement ([string | int $keyName], [mixed $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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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" => "127.0.0.1",
"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");
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], [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 queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public increment ([string $keyName], [mixed $value])
Increment of given $keyName by $value
public decrement ([string $keyName], [mixed $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", [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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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");
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], [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 queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public increment ([string $keyName], [mixed $value])
Increment of given $keyName by $value
public decrement ([string $keyName], [mixed $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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface, Serializable
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");
public get (mixed $keyName, [mixed $lifetime])
Returns a cached content
public save ([string $keyName], [string $content], [int $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 queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string | int $keyName], [int $lifetime])
Checks if cache exists and it hasn’t expired
public increment ([string $keyName], [mixed $value])
Increment of given $keyName by $value
public decrement ([string $keyName], [mixed $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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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");
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], [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 queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public collection->remove(...) gc ()
gc
public increment (int | string $keyName, [mixed $value])
Increment of a given key by $value
public decrement (int | string $keyName, [mixed $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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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");
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], [int $lifetime], [boolean $stopBuffer])
Stores cached content into the file backend and stops the frontend
<?php
$cache->save("my-key", $data);
// Save data termlessly
$cache->save("my-key", $data, -1);
public delete (int | string $keyName)
Deletes a value from the cache by its key
public queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public increment ([string $keyName], [mixed $value])
Increment of given $keyName by $value
public decrement ([string $keyName], [mixed $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
extends abstract class Phalcon\Cache\Backend
implements Phalcon\Cache\BackendInterface
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");
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], [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 queryKeys ([mixed $prefix])
Query the existing cached keys.
<?php
$cache->save("users-ids", [1, 2, 3]);
$cache->save("projects-ids", [4, 5, 6]);
var_dump($cache->queryKeys("users")); // ["users-ids"]
public exists ([string $keyName], [int $lifetime])
Checks if cache exists and it isn’t expired
public increment (string $keyName, [mixed $value])
Atomic increment of a given key, by number $value
public decrement (string $keyName, [mixed $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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Cache\FrontendInterface
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(
[
"lifetime" => 172800,
]
);
//Create a MongoDB cache
$cache = new \Phalcon\Cache\Backend\Mongo(
$frontCache,
[
"server" => "mongodb://localhost",
"db" => "caches",
"collection" => "images",
]
);
$cacheKey = "some-image.jpg.cache";
// Try to get cached image
$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;
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 beforeStore (mixed $data)
Serializes data before storing them
public afterRetrieve (mixed $data)
Unserializes data after retrieval
implements Phalcon\Cache\FrontendInterface
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/",
]
);
$cacheKey = "robots_order_id.cache";
// Try to get cached records
$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";
}
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
extends class Phalcon\Cache\Frontend\Data
implements Phalcon\Cache\FrontendInterface
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(
[
"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,
[
"cacheDir" => "../app/cache/",
]
);
$cacheKey = "robots_order_id.cache";
// Try to get cached records
$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";
}
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
implements Phalcon\Cache\FrontendInterface
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(
[
"lifetime" => 172800,
]
);
// Create the Cache setting memcached connection options
$cache = new \Phalcon\Cache\Backend\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");
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 beforeStore (mixed $data)
Serializes data before storing them
public afterRetrieve (mixed $data)
Unserializes data after retrieval
extends class Phalcon\Cache\Frontend\Data
implements Phalcon\Cache\FrontendInterface
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/",
]
);
$cacheKey = "robots_order_id.cache";
// Try to get cached records
$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";
}
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
implements Phalcon\Cache\FrontendInterface
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,
[
"host" => "localhost",
"port" => "11211",
]
);
$cacheKey = "robots_order_id.cache";
// This Frontend always return the data as it's returned by the backend
$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(
[
"order" => "id",
]
);
$cache->save($cacheKey, $robots);
}
// Use $robots :)
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
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
implements Phalcon\Cache\FrontendInterface
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;
* }
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 beforeStore (mixed $data)
Serializes data before storing them
public afterRetrieve (mixed $data)
Unserializes data after retrieval
Allows to read to chained backend adapters writing to multiple backends
<?php
use Phalcon\Cache\Frontend\Data as DataFrontend;
use Phalcon\Cache\Multiple;
use Phalcon\Cache\Backend\Apc as ApcCache;
use Phalcon\Cache\Backend\Memcache as MemcacheCache;
use Phalcon\Cache\Backend\File as FileCache;
$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);
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, [int $lifetime])
Returns a cached content reading the internal backends
public start (string | int $keyName, [int $lifetime])
Starts every backend
public save ([string $keyName], [string $content], [int $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 exists ([string | int $keyName], [int $lifetime])
Checks if cache exists in at least one backend
public flush ()
Flush all backend(s)
extends abstract class Phalcon\Application
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
This component allows to create CLI applications using Phalcon
public addModules (array $modules)
Merge modules with the existing ones
<?php
$application->addModules(
[
"admin" => [
"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
extends class Phalcon\Application\Exception
implements Throwable
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
extends abstract class Phalcon\Dispatcher
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\DispatcherInterface, Phalcon\Cli\DispatcherInterface
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([]);
$handle = $dispatcher->dispatch();
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
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 latest 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 (mixed $value, [mixed $cache]) inherited from Phalcon\Dispatcher
Enable/Disable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinding(true, 'cache');
return $dispatcher;
});
public setModelBinder (Phalcon\Mvc\Model\BinderInterface $modelBinder, [mixed $cache]) inherited from Phalcon\Dispatcher
Enable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinder(new Binder(), 'cache');
return $dispatcher;
});
public getModelBinder () inherited from Phalcon\Dispatcher
Gets model binder
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(
[
"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 getBoundModels () inherited from Phalcon\Dispatcher
Returns bound models from binder instance
<?php
class UserController extends Controller
{
public function showAction(User $user)
{
$boundModels = $this->dispatcher->getBoundModels(); // return array with $user
}
}
protected _resolveEmptyProperties () inherited from Phalcon\Dispatcher
Set empty properties to their defaults (where defaults are available)
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Di\InjectionAwareInterface
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(
[
"module" => "main",
"task" => "videos",
"action" => "process",
]
);
echo $router->getTaskName();
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(
[
"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 processed module name
public getTaskName ()
Returns processed 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
extends class Phalcon\Exception
implements Throwable
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
This class represents every route added to the router
string DEFAULT_DELIMITER
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",
[
"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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Cli\TaskInterface
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()
{
}
}
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
implements ArrayAccess, Countable
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(
[
"database" => [
"adapter" => "Mysql",
"host" => "localhost",
"username" => "scott",
"password" => "cheetah",
"dbname" => "test_db",
],
"phalcon" => [
"controllersDir" => "../app/controllers/",
"modelsDir" => "../app/models/",
"viewsDir" => "../app/views/",
],
]
);
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"] = [
"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(
[
"database" => [
"host" => "localhost",
],
]
);
$globalConfig->merge($appConfig);
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)
extends class Phalcon\Config
implements Countable, ArrayAccess
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
);
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",
],
],
];
protected _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"] = [
"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(
[
"database" => [
"host" => "localhost",
],
]
);
$globalConfig->merge($appConfig);
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)
extends class Phalcon\Config
implements Countable, ArrayAccess
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;
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"] = [
"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(
[
"database" => [
"host" => "localhost",
],
]
);
$globalConfig->merge($appConfig);
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)
extends class Phalcon\Config
implements Countable, ArrayAccess
Reads php files and converts them to Phalcon\Config objects.
Given the next configuration file:
<?php
<?php
return [
"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\Php("path/config.php");
echo $config->phalcon->controllersDir;
echo $config->database->username;
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"] = [
"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(
[
"database" => [
"host" => "localhost",
],
]
);
$globalConfig->merge($appConfig);
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)
extends class Phalcon\Config
implements Countable, ArrayAccess
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;
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"] = [
"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(
[
"database" => [
"host" => "localhost",
],
]
);
$globalConfig->merge($appConfig);
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)
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\CryptInterface
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);
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
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
extends class Phalcon\Exception
implements Throwable
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
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(
[
"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;
}
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
implements Phalcon\Db\AdapterInterface, Phalcon\Events\EventsAwareInterface
Base class for Phalcon\Db adapters
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,
[
"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",
["Astro Boy", 1952],
["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",
[
"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",
["name"],
["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",
["name"],
["New Astro Boy"],
[
"conditions" => "id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
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",
[
"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 escapeIdentifier (array | string $identifier)
Escapes a column/table/schema name
<?php
$escapedTable = $connection->escapeIdentifier(
"robots"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"robots",
]
);
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",
[
$connection->getDefaultIdValue(),
"Astro Boy",
1952,
],
[
"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",
[
"Astro Boy",
$connection->getDefaultValue()
],
[
"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 parameters
public array getSQLBindTypes ()
Active SQL statement in the object
abstract public connect ([array $descriptor]) inherited from Phalcon\Db\AdapterInterface
...
abstract public query (mixed $sqlStatement, [mixed $placeholders], [mixed $dataTypes]) inherited from Phalcon\Db\AdapterInterface
...
abstract public execute (mixed $sqlStatement, [mixed $placeholders], [mixed $dataTypes]) inherited from Phalcon\Db\AdapterInterface
...
abstract public affectedRows () inherited from Phalcon\Db\AdapterInterface
...
abstract public close () inherited from Phalcon\Db\AdapterInterface
...
abstract public escapeString (mixed $str) inherited from Phalcon\Db\AdapterInterface
...
abstract public lastInsertId ([mixed $sequenceName]) inherited from Phalcon\Db\AdapterInterface
...
abstract public begin ([mixed $nesting]) inherited from Phalcon\Db\AdapterInterface
...
abstract public rollback ([mixed $nesting]) inherited from Phalcon\Db\AdapterInterface
...
abstract public commit ([mixed $nesting]) inherited from Phalcon\Db\AdapterInterface
...
abstract public isUnderTransaction () inherited from Phalcon\Db\AdapterInterface
...
abstract public getInternalHandler () inherited from Phalcon\Db\AdapterInterface
...
abstract public describeColumns (mixed $table, [mixed $schema]) inherited from Phalcon\Db\AdapterInterface
...
extends abstract class Phalcon\Db\Adapter
implements Phalcon\Events\EventsAwareInterface, Phalcon\Db\AdapterInterface
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);
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 = ?",
[
"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 (?, ?)",
[
1,
"Astro Boy",
]
);
public affectedRows ()
Returns the number of affected rows by the latest 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 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:",
[
"Bender",
]
)
);
public int | boolean lastInsertId ([string $sequenceName])
Returns the insert id for the auto_increment/serial column inserted in the latest executed SQL statement
<?php
// Inserting a new robot
$success = $connection->insert(
"robots",
[
"Astro Boy",
1952,
],
[
"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();
// true
var_dump(
$connection->isUnderTransaction()
);
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,
[
"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",
["Astro Boy", 1952],
["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",
[
"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",
["name"],
["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",
["name"],
["New Astro Boy"],
[
"conditions" => "id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
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",
[
"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 escapeIdentifier (array | string $identifier) inherited from Phalcon\Db\Adapter
Escapes a column/table/schema name
<?php
$escapedTable = $connection->escapeIdentifier(
"robots"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"robots",
]
);
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",
[
$connection->getDefaultIdValue(),
"Astro Boy",
1952,
],
[
"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",
[
"Astro Boy",
$connection->getDefaultValue()
],
[
"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 parameters
public array getSQLBindTypes () inherited from Phalcon\Db\Adapter
Active SQL statement in the object
abstract public describeColumns (mixed $table, [mixed $schema]) inherited from Phalcon\Db\AdapterInterface
...
extends abstract class Phalcon\Db\Adapter\Pdo
implements Phalcon\Db\AdapterInterface, Phalcon\Events\EventsAwareInterface
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);
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 = ?",
[
"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 (?, ?)",
[
1,
"Astro Boy",
]
);
public affectedRows () inherited from Phalcon\Db\Adapter\Pdo
Returns the number of affected rows by the latest 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:",
[
"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 latest executed SQL statement
<?php
// Inserting a new robot
$success = $connection->insert(
"robots",
[
"Astro Boy",
1952,
],
[
"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();
// true
var_dump(
$connection->isUnderTransaction()
);
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,
[
"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",
["Astro Boy", 1952],
["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",
[
"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",
["name"],
["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",
["name"],
["New Astro Boy"],
[
"conditions" => "id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
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",
[
"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 escapeIdentifier (array | string $identifier) inherited from Phalcon\Db\Adapter
Escapes a column/table/schema name
<?php
$escapedTable = $connection->escapeIdentifier(
"robots"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"robots",
]
);
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",
[
$connection->getDefaultIdValue(),
"Astro Boy",
1952,
],
[
"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",
[
"Astro Boy",
$connection->getDefaultValue()
],
[
"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 parameters
public array getSQLBindTypes () inherited from Phalcon\Db\Adapter
Active SQL statement in the object
extends abstract class Phalcon\Db\Adapter\Pdo
implements Phalcon\Db\AdapterInterface, Phalcon\Events\EventsAwareInterface
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);
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",
[
$connection->getDefaultIdValue(),
"Astro Boy",
1952,
],
[
"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 = ?",
[
"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 (?, ?)",
[
1,
"Astro Boy",
]
);
public affectedRows () inherited from Phalcon\Db\Adapter\Pdo
Returns the number of affected rows by the latest 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:",
[
"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 latest executed SQL statement
<?php
// Inserting a new robot
$success = $connection->insert(
"robots",
[
"Astro Boy",
1952,
],
[
"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();
// true
var_dump(
$connection->isUnderTransaction()
);
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,
[
"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",
["Astro Boy", 1952],
["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",
[
"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",
["name"],
["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",
["name"],
["New Astro Boy"],
[
"conditions" => "id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
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",
[
"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 escapeIdentifier (array | string $identifier) inherited from Phalcon\Db\Adapter
Escapes a column/table/schema name
<?php
$escapedTable = $connection->escapeIdentifier(
"robots"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"robots",
]
);
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",
[
"Astro Boy",
$connection->getDefaultValue()
],
[
"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 parameters
public array getSQLBindTypes () inherited from Phalcon\Db\Adapter
Active SQL statement in the object
extends abstract class Phalcon\Db\Adapter\Pdo
implements Phalcon\Db\AdapterInterface, Phalcon\Events\EventsAwareInterface
Specific functions for the Sqlite database system
<?php
use Phalcon\Db\Adapter\Pdo\Sqlite;
$connection = new Sqlite(
[
"dbname" => "/tmp/test.sqlite",
]
);
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",
[
"Astro Boy",
$connection->getDefaultValue(),
],
[
"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 = ?",
[
"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 (?, ?)",
[
1,
"Astro Boy",
]
);
public affectedRows () inherited from Phalcon\Db\Adapter\Pdo
Returns the number of affected rows by the latest 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:",
[
"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 latest executed SQL statement
<?php
// Inserting a new robot
$success = $connection->insert(
"robots",
[
"Astro Boy",
1952,
],
[
"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();
// true
var_dump(
$connection->isUnderTransaction()
);
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,
[
"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",
["Astro Boy", 1952],
["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",
[
"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",
["name"],
["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",
["name"],
["New Astro Boy"],
[
"conditions" => "id = ?",
"bind" => [$some_unsafe_id],
"bindTypes" => [PDO::PARAM_INT], // use only if you use $dataTypes param
],
[
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",
[
"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 escapeIdentifier (array | string $identifier) inherited from Phalcon\Db\Adapter
Escapes a column/table/schema name
<?php
$escapedTable = $connection->escapeIdentifier(
"robots"
);
$escapedTable = $connection->escapeIdentifier(
[
"store",
"robots",
]
);
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",
[
$connection->getDefaultIdValue(),
"Astro Boy",
1952,
],
[
"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 parameters
public array getSQLBindTypes () inherited from Phalcon\Db\Adapter
Active SQL statement in the object
implements Phalcon\Db\ColumnInterface
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",
[
"type" => Column::TYPE_INTEGER,
"size" => 10,
"unsigned" => true,
"notNull" => true,
"autoIncrement" => true,
"first" => true,
]
);
// Add column to existing table
$connection->addColumn("robots", null, $column);
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
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
implements Phalcon\Db\DialectInterface
This is the base class to each database dialect. This implements common methods to transform intermediate code into its RDBMS related syntax
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(
[
"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
...
extends abstract class Phalcon\Db\Dialect
implements Phalcon\Db\DialectInterface
Generates database specific SQL for the MySQL RDBMS
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 truncateTable (mixed $tableName, mixed $schemaName)
Generates SQL to truncate 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(
[
"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
extends abstract class Phalcon\Db\Dialect
implements Phalcon\Db\DialectInterface
Generates database specific SQL for the PostgreSQL RDBMS
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 truncateTable (mixed $tableName, mixed $schemaName)
Generates SQL to truncate 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 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 _castDefault (Phalcon\Db\ColumnInterface $column)
...
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(
[
"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
extends abstract class Phalcon\Db\Dialect
implements Phalcon\Db\DialectInterface
Generates database specific SQL for the Sqlite RDBMS
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 truncateTable (mixed $tableName, mixed $schemaName)
Generates SQL to truncate 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(
[
"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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Db\IndexInterface
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
<?php
// Define new unique index
$index_unique = new \Phalcon\Db\Index(
'column_UNIQUE',
[
'column',
'column'
],
'UNIQUE'
);
// Define new primary index
$index_primary = new \Phalcon\Db\Index(
'PRIMARY',
[
'column'
]
);
// Add index to existing table
$connection->addIndex("robots", null, $index_unique);
$connection->addIndex("robots", null, $index_primary);
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
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";
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
This class identifies each profile in a Phalcon\Db\Profiler
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
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();
public getValue ()
Raw value without quoting or formatting
public __toString ()
Raw value without quoting or formatting
public __construct (mixed $value)
Phalcon\Db\RawValue constructor
implements Phalcon\Db\ReferenceInterface
Allows to define reference constraints on tables
<?php
$reference = new \Phalcon\Db\Reference(
"field_fk",
[
"referencedSchema" => "invoicing",
"referencedTable" => "products",
"columns" => [
"product_type",
"product_code",
],
"referencedColumns" => [
"type",
"code",
],
]
);
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
implements Phalcon\Db\ResultInterface
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);
}
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"
);
// Move to third row on result
$result->dataSeek(2);
// Fetch third row
$row = $result->fetch();
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
Provides debug capabilities to Phalcon applications
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
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);
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 ([array $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);
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\DiInterface, ArrayAccess
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
use Phalcon\Di;
use Phalcon\Http\Request;
$di = new Di();
// Using a string definition
$di->set("request", Request::class, true);
// Using an anonymous function
$di->setShared(
"request",
function () {
return new Request();
}
);
$request = $di->getRequest();
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 offsetSet (mixed $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 (mixed $method, [mixed $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
extends class Phalcon\Exception
implements Throwable
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
extends class Phalcon\Di
implements ArrayAccess, Phalcon\DiInterface
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
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 offsetSet (mixed $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 (mixed $method, [mixed $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
extends class Phalcon\Di\FactoryDefault
implements Phalcon\DiInterface, ArrayAccess
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
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 offsetSet (mixed $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 (mixed $method, [mixed $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
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
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
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
implements Phalcon\Di\ServiceInterface
Represents individually a service in the services container
<?php
$service = new \Phalcon\Di\Service(
"request",
"Phalcon\\Http\\Request"
);
$request = service->resolve();
<?php
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
This class builds instances based on complex definitions
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
implements Phalcon\DispatcherInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
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.
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
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 (mixed $value, [mixed $cache])
Enable/Disable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinding(true, 'cache');
return $dispatcher;
});
public setModelBinder (Phalcon\Mvc\Model\BinderInterface $modelBinder, [mixed $cache])
Enable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinder(new Binder(), 'cache');
return $dispatcher;
});
public getModelBinder ()
Gets model binder
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(
[
"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])
...
public getBoundModels ()
Returns bound models from binder instance
<?php
class UserController extends Controller
{
public function showAction(User $user)
{
$boundModels = $this->dispatcher->getBoundModels(); // return array with $user
}
}
protected _resolveEmptyProperties ()
Set empty properties to their defaults (where defaults are available)
implements Phalcon\EscaperInterface
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
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Events\EventInterface
This class offers contextual information of a fired event in the EventsManager
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.
<?php
if ($event->isCancelable()) {
$event->stop();
}
public isStopped ()
Check whether the event is currently stopped.
public isCancelable ()
Check whether the event is cancelable.
<?php
if ($event->isCancelable()) {
$event->stop();
}
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Events\ManagerInterface
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.
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
extends class Exception
implements Throwable
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
implements Phalcon\FilterInterface
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"
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
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\FlashInterface, Phalcon\Di\InjectionAwareInterface
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");
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
abstract public message (mixed $type, mixed $message) inherited from Phalcon\FlashInterface
...
extends abstract class Phalcon\Flash
implements Phalcon\Di\InjectionAwareInterface, Phalcon\FlashInterface
This is a variant of the Phalcon\Flash that immediately outputs any message passed to it
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
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Flash
implements Phalcon\Di\InjectionAwareInterface, Phalcon\FlashInterface
Temporarily stores the messages in session, then messages can be printed in the next request
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);
implements Phalcon\Forms\ElementInterface
This is a base class for form elements
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
...
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=check] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=date] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=email] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=file] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=number] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=password] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=radio] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component SELECT (choice) for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=submit] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component INPUT[type=text] for forms
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
extends abstract class Phalcon\Forms\Element
implements Phalcon\Forms\ElementInterface
Component TEXTAREA for forms
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
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Countable, Iterator, Traversable
This component allows to build forms using an object-oriented interface
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
public 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
implements Phalcon\Http\CookieInterface, Phalcon\Di\InjectionAwareInterface
Provide OO wrappers to manage a HTTP cookie
public __construct (string $name, [mixed $value], [int $expire], [string $path], [boolean $secure], [string $domain], [boolean $httpOnly])
Phalcon\Http\Cookie constructor
public setDI (Phalcon\DiInterface $dependencyInjector)
Sets the dependency injector
public getDI ()
Returns the internal dependency injector
public Phalcon\Http\Cookie setValue (string $value)
Sets the cookie’s value
public mixed getValue ([string | array $filters], [string $defaultValue])
Returns the cookie’s value
public send ()
Sends the cookie to the HTTP client Stores the cookie definition in session
public restore ()
Reads the cookie-related info from the SESSION to restore the cookie as it was set This method is automatically called internally so normally you don’t need to call it
public delete ()
Deletes the cookie by setting an expire time in the past
public useEncryption (mixed $useEncryption)
Sets if the cookie must be encrypted/decrypted automatically
public isUsingEncryption ()
Check if the cookie is using implicit encryption
public setExpiration (mixed $expire)
Sets the cookie’s expiration time
public getExpiration ()
Returns the current expiration time
public setPath (mixed $path)
Sets the cookie’s expiration time
public getName ()
Returns the current cookie’s name
public getPath ()
Returns the current cookie’s path
public setDomain (mixed $domain)
Sets the domain that the cookie is available to
public getDomain ()
Returns the domain that the cookie is available to
public setSecure (mixed $secure)
Sets if the cookie must only be sent when the connection is secure (HTTPS)
public getSecure ()
Returns whether the cookie must only be sent when the connection is secure (HTTPS)
public setHttpOnly (mixed $httpOnly)
Sets if the cookie is accessible only through the HTTP protocol
public getHttpOnly ()
Returns if the cookie is accessible only through the HTTP protocol
public __toString ()
Magic __toString method converts the cookie’s value to string
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Http\RequestInterface, Phalcon\Di\InjectionAwareInterface
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() && $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
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 searches 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
<?php
$_SERVER = [
"PHP_AUTH_USER" => "phalcon",
"PHP_AUTH_PW" => "secret",
];
$headers = $request->getHeaders();
echo $headers["Authorization"]; // Basic cGhhbGNvbjpzZWNyZXQ=
public getHTTPReferer ()
Gets web page that refers active request. ie: http://www.google.com
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”]
final protected _getQualityHeader (mixed $serverIndex, mixed $name)
Process a request header and return an array of values with their qualities
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Http\Request\FileInterface
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";
}
}
}
}
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
implements Phalcon\Http\ResponseInterface, Phalcon\Di\InjectionAwareInterface
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();
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 cookies 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 established 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(
[
"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(
[
"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
implements Phalcon\Http\Response\CookiesInterface, Phalcon\Di\InjectionAwareInterface
This class is a bag to manage the cookies A cookies bag is automatically registered as part of the ‘response’ service in the DI
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Http\Response\HeadersInterface
This class is a bag to manage the response headers
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
integer NONE
integer WIDTH
integer HEIGHT
integer AUTO
integer INVERSE
integer PRECISE
integer TENSILE
integer HORIZONTAL
integer VERTICAL
implements Phalcon\Image\AdapterInterface
All image adapters must use this class
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
extends abstract class Phalcon\Image\Adapter
implements Phalcon\Image\AdapterInterface
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
extends abstract class Phalcon\Image\Adapter
implements Phalcon\Image\AdapterInterface
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";
}
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Events\EventsAwareInterface
This component helps to load your project classes automatically based on some conventions
<?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();
// Requiring this class will automatically include file vendor/example/adapter/Some.php
$adapter = new \Example\Adapter\Some();
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 ([mixed $prepend])
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
extends class Phalcon\Exception
implements Throwable
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
integer SPECIAL
integer CUSTOM
integer DEBUG
integer INFO
integer NOTICE
integer WARNING
integer ERROR
integer ALERT
integer CRITICAL
integer EMERGENCE
integer EMERGENCY
implements Phalcon\Logger\AdapterInterface
Base class for Phalcon\Logger adapters
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
abstract public getFormatter () inherited from Phalcon\Logger\AdapterInterface
...
abstract public close () inherited from Phalcon\Logger\AdapterInterface
...
extends abstract class Phalcon\Logger\Adapter
implements Phalcon\Logger\AdapterInterface
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();
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
extends abstract class Phalcon\Logger\Adapter
implements Phalcon\Logger\AdapterInterface
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");
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
extends abstract class Phalcon\Logger\Adapter
implements Phalcon\Logger\AdapterInterface
Sends logs to a valid PHP stream
<?php
use Phalcon\Logger;
use Phalcon\Logger\Adapter\Stream;
$logger = new Stream("php://stderr");
$logger->log("This is a message");
$logger->log(Logger::ERROR, "This is an error");
$logger->error("This is another error");
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
extends abstract class Phalcon\Logger\Adapter
implements Phalcon\Logger\AdapterInterface
Sends logs to the system logger
<?php
use Phalcon\Logger;
use Phalcon\Logger\Adapter\Syslog;
// LOG_USER is the only valid log type under Windows operating systems
$logger = new Syslog(
"ident",
[
"option" => LOG_CONS | LOG_NDELAY | LOG_PID,
"facility" => LOG_USER,
]
);
$logger->log("This is a message");
$logger->log(Logger::ERROR, "This is an error");
$logger->error("This is another error");
public __construct (string $name, [array $options])
Phalcon\Logger\Adapter\Syslog 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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Logger\FormatterInterface
This is a base class for logger formatters
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
...
extends abstract class Phalcon\Logger\Formatter
implements Phalcon\Logger\FormatterInterface
Formats messages so that they can be sent to FirePHP
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
extends abstract class Phalcon\Logger\Formatter
implements Phalcon\Logger\FormatterInterface
Formats messages using JSON encoding
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
extends abstract class Phalcon\Logger\Formatter
implements Phalcon\Logger\FormatterInterface
Formats messages using an one-line string
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
extends abstract class Phalcon\Logger\Formatter
implements Phalcon\Logger\FormatterInterface
Prepares a message to be used in a Syslog backend
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
Represents each item in a logging transaction
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
Handles multiples logger handlers
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
extends abstract class Phalcon\Application
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
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(
[
"frontend" => [
"className" => "Multiple\\Frontend\\Module",
"path" => "../apps/frontend/Module.php",
],
"backend" => [
"className" => "Multiple\\Backend\\Module",
"path" => "../apps/backend/Module.php",
],
]
);
}
}
$application = new MyApp();
$application->main();
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
extends class Phalcon\Application\Exception
implements Throwable
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
implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\CollectionInterface, Phalcon\Di\InjectionAwareInterface, Serializable
This component implements a high level abstraction for NoSQL databases which works with documents
integer OP_NONE
integer OP_CREATE
integer OP_UPDATE
integer OP_DELETE
integer DIRTY_STATE_PERSISTENT
integer DIRTY_STATE_TRANSIENT
integer DIRTY_STATE_DETACHED
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 (mixed $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()
{
// Old, deprecated syntax, use new one below
$this->validate(
new ExclusionIn(
[
"field" => "status",
"domain" => ["A", "I"],
]
)
);
if ($this->validationHasFailed() == true) {
return false;
}
}
}
<?php
use Phalcon\Validation\Validator\ExclusionIn as ExclusionIn;
use Phalcon\Validation;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$validator = new Validation();
$validator->add("status",
new ExclusionIn(
[
"domain" => ["A", "I"]
]
)
);
return $this->validate($validator);
}
}
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(
[
"field" => "status",
"domain" => ["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 ";
$messages = $robot->getMessages();
foreach ($messages 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
<?php
$robot = new Robot();
$robot->name = "MyRobot";
$robot->type = "Droid";
// Create only if robot with same name and type does not exist
$robot->createIfNotExist(
[
"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(
[
[
"type" => "mechanical",
]
]
);
echo "There are ", count(robots), "\n";
// Get and print virtual robots ordered by name
$robots = Robots::findFirst(
[
[
"type" => "virtual"
],
"order" => [
"name" => 1,
]
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// Get first 100 virtual robots ordered by name
$robots = Robots::find(
[
[
"type" => "virtual",
],
"order" => [
"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();
$robots = Robots::find();
foreach ($robots as $robot) {
$robot->delete();
}
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 document exists in the collection or not
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
implements Phalcon\Mvc\Collection\BehaviorInterface
This is an optional base class for ORM behaviors
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
extends abstract class Phalcon\Mvc\Collection\Behavior
implements Phalcon\Mvc\Collection\BehaviorInterface
Instead of permanently delete a record it marks the record as deleted changing the value of a flag column
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
extends abstract class Phalcon\Mvc\Collection\Behavior
implements Phalcon\Mvc\Collection\BehaviorInterface
Allows to automatically update a model’s attribute saving the datetime when a record is created or updated
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
implements Phalcon\Mvc\EntityInterface, ArrayAccess
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].
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
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);
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ControllerInterface
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(
[
"controller" => "people",
"action" => "index",
]
);
}
}
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
extends abstract class Phalcon\Dispatcher
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\DispatcherInterface, Phalcon\Mvc\DispatcherInterface
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([]);
$controller = $dispatcher->dispatch();
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
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 (mixed $value, [mixed $cache]) inherited from Phalcon\Dispatcher
Enable/Disable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinding(true, 'cache');
return $dispatcher;
});
public setModelBinder (Phalcon\Mvc\Model\BinderInterface $modelBinder, [mixed $cache]) inherited from Phalcon\Dispatcher
Enable model binding during dispatch
<?php
$di->set('dispatcher', function() {
$dispatcher = new Dispatcher();
$dispatcher->setModelBinder(new Binder(), 'cache');
return $dispatcher;
});
public getModelBinder () inherited from Phalcon\Dispatcher
Gets model binder
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(
[
"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
...
public getBoundModels () inherited from Phalcon\Dispatcher
Returns bound models from binder instance
<?php
class UserController extends Controller
{
public function showAction(User $user)
{
$boundModels = $this->dispatcher->getBoundModels(); // return array with $user
}
}
protected _resolveEmptyProperties () inherited from Phalcon\Dispatcher
Set empty properties to their defaults (where defaults are available)
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, ArrayAccess
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();
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(
$app["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 afterBinding (callable $handler)
Appends a afterBinding middleware to be called after model binding
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 getHandlers ()
Returns the internal handlers attached to the application
public getModelBinder ()
Gets model binder
public setModelBinder (Phalcon\Mvc\Model\BinderInterface $modelBinder, [mixed $cache])
Sets model binder
<?php
$micro = new Micro($di);
$micro->setModelBinder(new Binder(), 'cache');
public getBoundModels ()
Returns bound models from binder instance
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
implements Phalcon\Mvc\Micro\CollectionInterface
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);
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
extends class Phalcon\Exception
implements Throwable
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
Lazy-Load of handlers for Mvc\Micro using auto-loading
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
public mixed callMethod (string $method, array $arguments, [Phalcon\Mvc\Model\BinderInterface $modelBinder])
Calling __call method
implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\ModelInterface, Phalcon\Mvc\Model\ResultInterface, Phalcon\Di\InjectionAwareInterface, Serializable, JsonSerializable
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: ";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo message;
}
} else {
echo "Great, a new robot was saved successfully!";
}
integer OP_NONE
integer OP_CREATE
integer OP_UPDATE
integer OP_DELETE
integer DIRTY_STATE_PERSISTENT
integer DIRTY_STATE_TRANSIENT
integer DIRTY_STATE_DETACHED
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 the table name to which model should be mapped
public getSource ()
Returns the table name mapped in the model
protected setSchema (mixed $schema)
Sets schema name where the mapped table is located
public getSchema ()
Returns schema name where the mapped table 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(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
// Assign by db row, column map needed
$robot->assign(
$dbRow,
[
"db_type" => "type",
"db_name" => "name",
"db_year" => "year",
]
);
// Allow assign only name and year
$robot->assign(
$_POST,
null,
[
"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(),
[
"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(),
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
public static find ([mixed $parameters])
Query for 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])
Query the first record that matches 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(
[
"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 whether the current record already exists
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])
Counts 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])
Calculates the sum on a column for a result-set of rows that match the specified conditions
<?php
// How much are all robots?
$sum = Robots::sum(
[
"column" => "price",
]
);
echo "The total price of robots is ", $sum, "\n";
// How much are mechanical robots?
$sum = Robots::sum(
[
"type = 'mechanical'",
"column" => "price",
]
);
echo "The total price of mechanical robots is ", $sum, "\n";
public static mixed maximum ([array $parameters])
Returns the maximum value of a column for a result-set of rows that match the specified conditions
<?php
// What is the maximum robot id?
$id = Robots::maximum(
[
"column" => "id",
]
);
echo "The maximum robot id is: ", $id, "\n";
// What is the maximum id of mechanical robots?
$sum = Robots::maximum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The maximum robot id of mechanical robots is ", $id, "\n";
public static mixed minimum ([array $parameters])
Returns the minimum value of a column for a result-set of rows that match the specified conditions
<?php
// What is the minimum robot id?
$id = Robots::minimum(
[
"column" => "id",
]
);
echo "The minimum robot id is: ", $id;
// What is the minimum id of mechanical robots?
$sum = Robots::minimum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The minimum robot id of mechanical robots is ", $id;
public static double average ([array $parameters])
Returns the average value on a column for a result-set of rows matching the specified conditions
<?php
// What's the average price of robots?
$average = Robots::average(
[
"column" => "price",
]
);
echo "The average price is ", $average, "\n";
// What's the average price of mechanical robots?
$average = Robots::average(
[
"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(
[
"domain" => [
"A",
"I",
],
]
)
);
return $this->validate($validator);
}
}
public validationHasFailed ()
Check whether validation process has generated any messages
<?php
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\ExclusionIn;
class Subscriptors extends Model
{
public function validation()
{
$validator = new Validation();
$validator->validate(
"status",
new ExclusionIn(
[
"domain" => [
"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 ";
$messages = $robot->getMessages();
foreach ($messages 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(
[
"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();
$robots = Robots::find("type = 'mechanical'");
foreach ($robots 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(
[
"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(
[
"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(
[
"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(
[
"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 reverse 1-1 or n-1 relation 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 1-n relation 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 an n-n relation 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(
[
"onCreate" => [
"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.
<?php
$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []
$robots->deleted = 'Y';
$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
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
implements Phalcon\Mvc\Model\BehaviorInterface
This is an optional base class for ORM behaviors
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
extends abstract class Phalcon\Mvc\Model\Behavior
implements Phalcon\Mvc\Model\BehaviorInterface
Instead of permanently delete a record it marks the record as deleted changing the value of a flag column
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
extends abstract class Phalcon\Mvc\Model\Behavior
implements Phalcon\Mvc\Model\BehaviorInterface
Allows to automatically update a model’s attribute saving the datetime when a record is created or updated
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
implements Phalcon\Mvc\Model\BinderInterface
Phalcon\Mvc\Model\Binding
This is an class for binding models into params for handler
public getBoundModels ()
Array for storing active bound models
public getOriginalValues ()
Array for original values
public __construct ([Phalcon\Cache\BackendInterface $cache])
Phalcon\Mvc\Model\Binder constructor
public setCache (Phalcon\Cache\BackendInterface $cache)
Gets cache instance
public getCache ()
Sets cache instance
public bindToHandler (mixed $handler, array $params, mixed $cacheKey, [mixed $methodName])
Bind models into params in proper handler
protected getParamsFromCache (mixed $cacheKey)
Get params classes from cache by key
protected getParamsFromReflection (mixed $handler, array $params, mixed $cacheKey, mixed $methodName)
Get modified params for handler using reflection
implements Phalcon\Mvc\Model\CriteriaInterface, Phalcon\Di\InjectionAwareInterface
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();
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(
[
"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.
<?php
$criteria->limit(100);
$criteria->limit(100, 200);
$criteria->limit("100", "200");
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Mvc\Model\ManagerInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
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);
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
implements Phalcon\Mvc\Model\MessageInterface
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);
}
}
}
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
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\Model\MetaDataInterface
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);
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
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,
[
"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(),
[
"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(),
[
"modified_at" => true,
]
);
public setEmptyStringAttributes (Phalcon\Mvc\ModelInterface $model, array $attributes)
Set the attributes that allow empty string values
<?php
$metaData->setEmptyStringAttributes(
new Robots(),
[
"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
...
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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();
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
Stores model meta-data in PHP files.
<?php
$metaData = new \Phalcon\Mvc\Model\Metadata\Files(
[
"metaDataDir" => "app/cache/metadata/",
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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();
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"servers" => [
[
"host" => "localhost",
"port" => 11211,
"weight" => 1,
],
],
"client" => [
Memcached::OPT_HASH => Memcached::HASH_MD5,
Memcached::OPT_PREFIX_KEY => "prefix.",
],
"lifetime" => 3600,
"prefix" => "my_",
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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()
);
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
"host" => "localhost",
"port" => 11211,
"persistent" => false,
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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()
);
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
Stores model meta-data in memory. Data will be erased when the request finishes
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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();
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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,
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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()
);
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"prefix" => "my-app-id",
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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();
implements Phalcon\Mvc\Model\MetaData\StrategyInterface
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
implements Phalcon\Mvc\Model\MetaData\StrategyInterface
Queries the table meta-data in order to introspect the model’s metadata
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
extends abstract class Phalcon\Mvc\Model\MetaData
implements Phalcon\Mvc\Model\MetaDataInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
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
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,
[
"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(),
[
"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(),
[
"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(),
[
"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();
implements Phalcon\Mvc\Model\QueryInterface, Phalcon\Di\InjectionAwareInterface
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,
[
"name" => "Lamborghini",
]
);
foreach ($result as $row) {
echo "Name: ", $row->cars->name, "\n";
echo "Price: ", $row->cars->price, "\n";
echo "Taxes: ", $row->taxes, "\n";
}
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
implements Phalcon\Mvc\Model\Query\BuilderInterface, Phalcon\Di\InjectionAwareInterface
Helps to create PHQL queries using an OO interface
<?php
$params = [
"models" => ["Users"],
"columns" => ["id", "name", "status"],
"conditions" => [
[
"created > :min: AND created < :max:",
[
"min" => "2013-01-01",
"max" => "2014-01-01",
],
[
"min" => PDO::PARAM_STR,
"max" => PDO::PARAM_STR,
],
],
],
// or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'",
"group" => ["id", "name"],
"having" => "name = 'Kamil'",
"order" => ["name", "id"],
"limit" => 20,
"offset" => 20,
// or "limit" => [20, 20],
];
$queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params);
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(
[
"id",
"name",
]
);
$builder->columns(
[
"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(
[
"Robots",
"RobotsParts",
]
);
$builder->from(
[
"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' specifying conditions
$builder->join("Robots", "Robots.id = RobotsParts.robots_id");
// Inner Join model 'Robots' specifying conditions and alias
$builder->join("Robots", "r.id = RobotsParts.robots_id", "r");
// Left Join model 'Robots' specifying 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' specifying conditions
$builder->innerJoin("Robots", "Robots.id = RobotsParts.robots_id");
// Inner Join model 'Robots' specifying 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:",
[
"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:",
[
"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:",
[
"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(["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);
$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(
[
"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.
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");
public static string parsePHQL (string $phql)
Parses a PHQL statement returning an intermediate representation (IR)
implements Phalcon\Mvc\Model\Query\StatusInterface
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,
[
"id" => 100,
"name" => "Astroy Boy",
"type" => "mechanical",
"year" => 1959,
]
);
// Check if the update was successful
if ($status->success() === true) {
echo "OK";
}
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
implements Phalcon\Mvc\Model\RelationInterface
This class represents a relationship between two models
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
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
implements Phalcon\Mvc\Model\ResultsetInterface, Iterator, Traversable, SeekableIterator, Countable, ArrayAccess, Serializable, JsonSerializable
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();
}
integer TYPE_RESULT_FULL
integer TYPE_RESULT_PARTIAL
integer HYDRATE_RECORDS
integer HYDRATE_OBJECTS
integer HYDRATE_ARRAYS
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
...
extends abstract class Phalcon\Mvc\Model\Resultset
implements JsonSerializable, Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface
Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required
integer TYPE_RESULT_FULL
integer TYPE_RESULT_PARTIAL
integer HYDRATE_RECORDS
integer HYDRATE_OBJECTS
integer HYDRATE_ARRAYS
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);
extends abstract class Phalcon\Mvc\Model\Resultset
implements JsonSerializable, Serializable, ArrayAccess, Countable, SeekableIterator, Traversable, Iterator, Phalcon\Mvc\Model\ResultsetInterface
Simple resultsets only contains a complete objects This class builds every complete object as it is required
integer TYPE_RESULT_FULL
integer TYPE_RESULT_PARTIAL
integer HYDRATE_RECORDS
integer HYDRATE_OBJECTS
integer HYDRATE_ARRAYS
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);
implements Phalcon\Mvc\EntityInterface, Phalcon\Mvc\Model\ResultInterface, ArrayAccess, JsonSerializable
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].
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
implements Phalcon\Mvc\Model\TransactionInterface
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();
}
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
extends class Phalcon\Mvc\Model\Exception
implements Throwable
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
extends class Phalcon\Mvc\Model\Transaction\Exception
implements Throwable
This class will be thrown to exit a try/catch block for isolated transactions
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
implements Phalcon\Mvc\Model\Transaction\ManagerInterface, Phalcon\Di\InjectionAwareInterface
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();
}
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
extends class Phalcon\Mvc\Model\Exception
implements Throwable
This exception is generated when a model fails to save a record Phalcon\Mvc\Model must be set up to have this behavior
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
implements Phalcon\Mvc\Model\ValidatorInterface
This is a base class for Phalcon\Mvc\Model validators
This class is only for backward compatibility reasons to use with Phalcon\Mvc\Collection. Otherwise please use the validators provided by Phalcon\Validation.
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
abstract public validate (Phalcon\Mvc\EntityInterface $record) inherited from Phalcon\Mvc\Model\ValidatorInterface
...
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Allows to validate if email fields has correct values
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\Email as EmailValidator;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new EmailValidator(
[
"field" => "electronic_mail",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Phalcon\Mvc\Model\Validator\ExclusionIn
Check if a value is not included into a list of values
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\ExclusionIn as ExclusionInValidator;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new ExclusionInValidator(
[
"field" => "status",
"domain" => ["A", "I"],
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Phalcon\Mvc\Model\Validator\InclusionIn
Check if a value is included into a list of values
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\InclusionIn as InclusionInValidator;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new InclusionInValidator(
[
"field" => "status",
"domain" => ["A", "I"],
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Phalcon\Mvc\Model\Validator\IP
Validates that a value is ipv4 address in valid range
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\Ip;
class Data extends \Phalcon\Mvc\Collection
{
public function validation()
{
// Any pubic IP
$this->validate(
new IP(
[
"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(
[
"field" => "ip_4",
"version" => IP::VERSION_4,
"message" => "IP address has to be correct",
]
)
);
// Any v6 address
$this->validate(
new IP(
[
"field" => "ip6",
"version" => IP::VERSION_6,
"allowPrivate" => true,
"message" => "IP address has to be correct",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Allows to validate if a field has a valid numeric format
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\Numericality as NumericalityValidator;
class Products extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new NumericalityValidator(
[
"field" => "price",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Allows to validate if a filed have a value different of null and empty string (“”)
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\PresenceOf;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new PresenceOf(
[
"field" => "name",
"message" => "The name is required",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Allows validate if the value of a field matches a regular expression
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\Regex as RegexValidator;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new RegexValidator(
[
"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;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Simply validates specified string length constraints
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\StringLength as StringLengthValidator;
class Subscriptors extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new StringLengthValidator(
[
"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;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
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
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Collection;
use Phalcon\Mvc\Model\Validator\Uniqueness;
class Subscriptors extends Collection
{
public function validation()
{
$this->validate(
new Uniqueness(
[
"field" => "email",
"message" => "Value of field 'email' is already present in another record",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
extends abstract class Phalcon\Mvc\Model\Validator
implements Phalcon\Mvc\Model\ValidatorInterface
Allows to validate if a field has a url format
This validator is only for use with Phalcon\Mvc\Collection. If you are using Phalcon\Mvc\Model, please use the validators provided by Phalcon\Validation.
<?php
use Phalcon\Mvc\Model\Validator\Url as UrlValidator;
class Posts extends \Phalcon\Mvc\Collection
{
public function validation()
{
$this->validate(
new UrlValidator(
[
"field" => "source_url",
]
)
);
if ($this->validationHasFailed() === true) {
return false;
}
}
}
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
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\RouterInterface, Phalcon\Events\EventsAwareInterface
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();
integer URI_SOURCE_GET_URL
integer URI_SOURCE_SERVER_REQUEST_URI
integer POSITION_FIRST
integer POSITION_LAST
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
extends class Phalcon\Mvc\Router
implements Phalcon\Events\EventsAwareInterface, Phalcon\Mvc\RouterInterface, Phalcon\Di\InjectionAwareInterface
A router that reads routes annotations from classes/resources
<?php
use Phalcon\Mvc\Router\Annotations;
$di->setShared(
"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;
}
);
integer URI_SOURCE_GET_URL
integer URI_SOURCE_SERVER_REQUEST_URI
integer POSITION_FIRST
integer POSITION_LAST
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Mvc\Router\GroupInterface
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(
[
"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" => "about",
"action" => "index",
]
);
//Add the group to the router
$router->mount($blog);
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
implements Phalcon\Mvc\Router\RouteInterface
This class represents every route added to the router
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(
[
"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",
[
"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",
[
"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",
[]
)->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(["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
implements Phalcon\Mvc\UrlInterface, Phalcon\Di\InjectionAwareInterface
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(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "2012",
]
);
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(
[
"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",
[
"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(
[
"for" => "logo-cdn",
]
);
public path ([mixed $path])
Generates a local path
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ViewInterface, Phalcon\Mvc\ViewBaseInterface
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();
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
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\View\EngineInterface
All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.
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
abstract public render (mixed $path, mixed $params, [mixed $mustClean]) inherited from Phalcon\Mvc\View\EngineInterface
...
extends abstract class Phalcon\Mvc\View\Engine
implements Phalcon\Mvc\View\EngineInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
Adapter to use PHP itself as templating engine
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
extends abstract class Phalcon\Mvc\View\Engine
implements Phalcon\Mvc\View\EngineInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Events\EventsAwareInterface
Designer friendly and fast template engine for PHP written in Zephir/C
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
implements Phalcon\Di\InjectionAwareInterface
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();
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
extends class Phalcon\Mvc\View\Exception
implements Throwable
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
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\Mvc\ViewBaseInterface
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,
]
);
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
implements Phalcon\Paginator\AdapterInterface
public setCurrentPage (mixed $page)
Set the current page number
public setLimit (mixed $limitRows)
Set current rows limit
public getLimit ()
Get current rows limit
abstract public getPaginate () inherited from Phalcon\Paginator\AdapterInterface
...
extends abstract class Phalcon\Paginator\Adapter
implements Phalcon\Paginator\AdapterInterface
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();
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
extends abstract class Phalcon\Paginator\Adapter
implements Phalcon\Paginator\AdapterInterface
Pagination using a PHP array as source of data
<?php
use Phalcon\Paginator\Adapter\NativeArray;
$paginator = new NativeArray(
[
"data" => [
["id" => 1, "name" => "Artichoke"],
["id" => 2, "name" => "Carrots"],
["id" => 3, "name" => "Beet"],
["id" => 4, "name" => "Lettuce"],
["id" => 5, "name" => ""],
],
"limit" => 2,
"page" => $currentPage,
]
);
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
extends abstract class Phalcon\Paginator\Adapter
implements Phalcon\Paginator\AdapterInterface
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,
]
);
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
extends class Phalcon\Exception
implements Throwable
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 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,
]
);
integer DEFAULT_DELAY
integer DEFAULT_PRIORITY
integer DEFAULT_TTR
string DEFAULT_TUBE
string DEFAULT_HOST
integer DEFAULT_PORT
public __construct ([array $parameters])
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.
extends class Phalcon\Exception
implements Throwable
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
Represents a job in a beanstalk queue
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
implements ArrayAccess, Countable, Iterator, Traversable
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.
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)
...
implements Phalcon\Di\InjectionAwareInterface
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
}
}
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
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) {
// ...
}
extends class Phalcon\Exception
implements Throwable
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
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:
Phalcon\Security\Random could be mainly useful for:
<?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
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
implements Phalcon\Session\AdapterInterface
Base class for Phalcon\Session adapters
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 ()
...
extends abstract class Phalcon\Session\Adapter
implements Phalcon\Session\AdapterInterface
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
...
extends abstract class Phalcon\Session\Adapter
implements Phalcon\Session\AdapterInterface
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");
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
...
extends abstract class Phalcon\Session\Adapter
implements Phalcon\Session\AdapterInterface
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");
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
...
extends abstract class Phalcon\Session\Adapter
implements Phalcon\Session\AdapterInterface
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");
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
...
implements Phalcon\Di\InjectionAwareInterface, Phalcon\Session\BagInterface, IteratorAggregate, Traversable, ArrayAccess, Countable
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;
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)
...
extends class Phalcon\Exception
implements Throwable
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
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.
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
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(
[
"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 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(
[
"signup/register",
"Register Here!"
]
);
echo Phalcon\Tag::linkTo(
[
"signup/register",
"Register Here!",
"class" => "btn-primary",
]
);
echo Phalcon\Tag::linkTo("http://phalconphp.com/", "Phalcon", false);
echo Phalcon\Tag::linkTo(
[
"http://phalconphp.com/",
"Phalcon Home",
false,
]
);
echo Phalcon\Tag::linkTo(
[
"http://phalconphp.com/",
"Phalcon Home",
"local" => false,
]
);
echo Phalcon\Tag::linkTo(
[
"action" => "http://phalconphp.com/",
"text" => "Phalcon Home",
"local" => false,
"target" => "_new"
]
);
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(
[
"name",
"size" => 30,
]
);
public static string numericField (array $parameters)
Builds a HTML input[type=”number”] tag
<?php
echo Phalcon\Tag::numericField(
[
"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(
[
"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(
[
"name",
"size" => 30,
]
);
public static string hiddenField (array $parameters)
Builds a HTML input[type=”hidden”] tag
<?php
echo Phalcon\Tag::hiddenField(
[
"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(
[
"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(
[
"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(
[
"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",
[
"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(
[
"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(
[
"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(
[
"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
public static tagHtmlClose (mixed $tagName, [mixed $useEol])
Builds a HTML tag closing tag
<?php
echo Phalcon\Tag::tagHtmlClose("script", true);
extends class Phalcon\Exception
implements Throwable
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
Generates a SELECT html tag using a static array of values or a Phalcon\Mvc\Model resultset
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
Provides utilities to work with texts
integer RANDOM_ALNUM
integer RANDOM_ALPHA
integer RANDOM_HEXDEC
integer RANDOM_NUMERIC
integer RANDOM_NOZERO
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
// "aloiwkqz"
echo Phalcon\Text::random(
Phalcon\Text::RANDOM_ALNUM
);
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/"
);
// /tmp/folder_1/folder_2/folder_3/
echo $str;
public static dynamic (mixed $text, [mixed $leftDelimiter], [mixed $rightDelimiter], [mixed $separator])
Generates random text in accordance with the template
<?php
// 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 {Bob|Mark|Jon}!");
// Hello my name is a Zyxep
echo Phalcon\Text::dynamic("[Hi/Hello], my name is a [Zyxep/Mark]!", "[", "]", "/");
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"
implements Phalcon\Translate\AdapterInterface
Base class for Phalcon\Translate adapters
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
abstract public query (mixed $index, [mixed $placeholders]) inherited from Phalcon\Translate\AdapterInterface
...
abstract public exists (mixed $index) inherited from Phalcon\Translate\AdapterInterface
...
extends abstract class Phalcon\Translate\Adapter
implements Phalcon\Translate\AdapterInterface, ArrayAccess
Allows to define translation lists using CSV file
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
extends abstract class Phalcon\Translate\Adapter
implements Phalcon\Translate\AdapterInterface, ArrayAccess
<?php
use Phalcon\Translate\Adapter\Gettext;
$adapter = new Gettext(
[
"locale" => "de_DE.UTF-8",
"defaultDomain" => "translations",
"directory" => "/path/to/application/locales",
"category" => LC_MESSAGES,
]
);
Allows translate using gettext
public getDirectory ()
public getDefaultDomain ()
public getLocale ()
public getCategory ()
public __construct (array $options)
Phalcon\Translate\Adapter\Gettext constructor
public query (mixed $index, [mixed $placeholders])
Returns the translation related to the given key.
<?php
$translator->query("你好 %name%!", ["name" => "Phalcon"]);
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
extends abstract class Phalcon\Translate\Adapter
implements Phalcon\Translate\AdapterInterface, ArrayAccess
Allows to define translation lists using PHP arrays
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Translate\InterpolatorInterface
public replacePlaceholders (mixed $translation, [mixed $placeholders])
Replaces placeholders by the values passed
implements Phalcon\Translate\InterpolatorInterface
public replacePlaceholders (mixed $translation, [mixed $placeholders])
Replaces placeholders by the values passed
extends abstract class Phalcon\Di\Injectable
implements Phalcon\Events\EventsAwareInterface, Phalcon\Di\InjectionAwareInterface, Phalcon\ValidationInterface
Allows to validate data using custom or built-in validators
public getData ()
...
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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
extends class Phalcon\Exception
implements Throwable
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
implements Phalcon\Validation\MessageInterface
Encapsulates validation info generated in the validation process
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 messages from serialization
implements Countable, ArrayAccess, Iterator, Traversable
Represents a group of validation messages
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 (mixed $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
implements Phalcon\Validation\ValidatorInterface
This is a base class for validators
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
Calls user function for validation
<?php
use Phalcon\Validation\Validator\Callback as CallbackValidator;
use Phalcon\Validation\Validator\Numericality as NumericalityValidator;
$validator->add(
["user", "admin"],
new CallbackValidator(
[
"message" => "There must be only an user or admin set",
"callback" => function($data) {
if (!empty($data->getUser()) && !empty($data->getAdmin())) {
return false;
}
return true;
}
]
)
);
$validator->add(
"amount",
new CallbackValidator(
[
"callback" => function($data) {
if (!empty($data->getProduct())) {
return new NumericalityValidator(
[
"message" => "Amount must be a number."
]
);
}
}
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends class Phalcon\Exception
implements Throwable
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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 "'
],
"domain" => [
"status" => [
"A",
"B",
],
"type" => [1, 2],
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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" => [
"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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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" => ["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],
]
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
]
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
],
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
]
]
)
);
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
]
]
)
);
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
extends abstract class Phalcon\Validation\CombinedFieldsValidator
implements Phalcon\Validation\ValidatorInterface
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;
}
]
)
);
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
protected isUniquenessModel (mixed $record, array $field, array $values)
Uniqueness method used for model
protected isUniquenessCollection (mixed $record, array $field, array $values)
Uniqueness method used for collection
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
extends abstract class Phalcon\Validation\Validator
implements Phalcon\Validation\ValidatorInterface
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",
]
]
)
);
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
This class allows to get the installed version of the framework
integer VERSION_MAJOR
integer VERSION_MEDIUM
integer VERSION_MINOR
integer VERSION_SPECIAL
integer VERSION_SPECIAL_NUMBER
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
);
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 ()
...
abstract public getName ()
...
abstract public getDescription ()
...
abstract public __toString ()
...
abstract public getName ()
...
abstract public getDescription ()
...
abstract public __toString ()
...
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)
...
abstract public parse (mixed $className)
...
abstract public static parseDocBlock (mixed $docBlock, [mixed $file], [mixed $line])
...
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])
...
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)
...
implements Phalcon\DispatcherInterface
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
...
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)
...
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 ()
...
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 ()
...
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])
...
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)
...
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)
...
abstract public getName ()
...
abstract public getColumns ()
...
abstract public getType ()
...
abstract public static __set_state (array $data)
...
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)
...
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 ()
...
implements ArrayAccess
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
...
abstract public setDI (Phalcon\DiInterface $dependencyInjector)
...
abstract public getDI ()
...
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)
...
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)
...
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)
...
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 ()
...
abstract public setEventsManager (Phalcon\Events\ManagerInterface $eventsManager)
...
abstract public getEventsManager ()
...
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)
...
abstract public add (mixed $name, mixed $handler)
...
abstract public sanitize (mixed $value, mixed $filters)
...
abstract public getFilters ()
...
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)
...
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])
...
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 ()
...
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 ()
...
abstract public getSize ()
...
abstract public getName ()
...
abstract public getTempName ()
...
abstract public getType ()
...
abstract public getRealType ()
...
abstract public moveTo (mixed $destination)
...
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])
...
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 ()
...
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)
...
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])
...
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])
...
abstract public format (mixed $message, mixed $type, mixed $timestamp, [mixed $context])
...
abstract public setId (mixed $id)
...
abstract public getId ()
...
abstract public getReservedAttributes ()
...
abstract public getSource ()
...
abstract public setConnectionService (mixed $connectionService)
...
abstract public getConnection ()
...
abstract public setDirtyState (mixed $dirtyState)
...
abstract public getDirtyState ()
...
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 ()
...
abstract public notify (mixed $type, Phalcon\Mvc\CollectionInterface $collection)
...
abstract public missingMethod (Phalcon\Mvc\CollectionInterface $collection, mixed $method, [mixed $arguments])
...
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)
...
implements Phalcon\DispatcherInterface
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
...
abstract public readAttribute (mixed $attribute)
...
abstract public writeAttribute (mixed $attribute, mixed $value)
...
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])
...
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 ()
...
abstract public notify (mixed $type, Phalcon\Mvc\ModelInterface $model)
...
abstract public missingMethod (Phalcon\Mvc\ModelInterface $model, mixed $method, [mixed $arguments])
...
abstract public getBoundModels ()
...
abstract public getCache ()
...
abstract public setCache (Phalcon\Cache\BackendInterface $cache)
...
abstract public bindToHandler (mixed $handler, array $params, mixed $cacheKey, [mixed $methodName])
...
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 ()
...
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)
...
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)
...
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)
...
abstract public getMetaData (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)
...
abstract public getColumnMaps (Phalcon\Mvc\ModelInterface $model, Phalcon\DiInterface $dependencyInjector)
...
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])
...
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 ()
...
abstract public getModel ()
...
abstract public getMessages ()
...
abstract public success ()
...
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 ()
...
abstract public getType ()
...
abstract public getFirst ()
...
abstract public getLast ()
...
abstract public setIsFresh (mixed $isFresh)
...
abstract public isFresh ()
...
abstract public getCache ()
...
abstract public toArray ()
...
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)
...
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 ()
...
abstract public getMessages ()
...
abstract public validate (Phalcon\Mvc\EntityInterface $record)
...
abstract public registerAutoloaders ([Phalcon\DiInterface $dependencyInjector])
...
abstract public registerServices (Phalcon\DiInterface $dependencyInjector)
...
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)
...
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 ()
...
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 ()
...
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])
...
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])
...
implements Phalcon\Mvc\ViewBaseInterface
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
...
abstract public getContent ()
...
abstract public partial (mixed $partialPath, [mixed $params])
...
abstract public render (mixed $path, mixed $params, [mixed $mustClean])
...
abstract public setCurrentPage (mixed $page)
...
abstract public getPaginate ()
...
abstract public setLimit (mixed $limit)
...
abstract public getLimit ()
...
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 ()
...
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)
...
abstract public t (mixed $translateKey, [mixed $placeholders])
...
abstract public query (mixed $index, [mixed $placeholders])
...
abstract public exists (mixed $index)
...
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)
...
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)
...
abstract public hasOption (mixed $key)
...
abstract public getOption (mixed $key, [mixed $defaultValue])
...
abstract public validate (Phalcon\Validation $validation, mixed $attribute)
...
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! :)