# Working with Models (Advanced)
## Hydration Modes
As mentioned previously, resultsets are collections of complete objects, this means that every returned result is an object representing a row in the database. These objects can be modified and saved again to persistence:
~~~
<?php
use Store\Toys\Robots;
$robots = Robots::find();
// Manipulating a resultset of complete objects
foreach ($robots as $robot) {
$robot->year = 2000;
$robot->save();
}
~~~
Sometimes records are obtained only to be presented to a user in read-only mode, in these cases it may be useful to change the way in which records are represented to facilitate their handling. The strategy used to represent objects returned in a resultset is called ‘hydration mode’:
~~~
<?php
use Phalcon\Mvc\Model\Resultset;
use Store\Toys\Robots;
$robots = Robots::find();
// Return every robot as an array
$robots->setHydrateMode(
Resultset::HYDRATE_ARRAYS
);
foreach ($robots as $robot) {
echo $robot["year"], PHP_EOL;
}
// Return every robot as a stdClass
$robots->setHydrateMode(
Resultset::HYDRATE_OBJECTS
);
foreach ($robots as $robot) {
echo $robot->year, PHP_EOL;
}
// Return every robot as a Robots instance
$robots->setHydrateMode(
Resultset::HYDRATE_RECORDS
);
foreach ($robots as $robot) {
echo $robot->year, PHP_EOL;
}
~~~
Hydration mode can also be passed as a parameter of ‘find’:
~~~
<?php
use Phalcon\Mvc\Model\Resultset;
use Store\Toys\Robots;
$robots = Robots::find(
[
"hydration" => Resultset::HYDRATE_ARRAYS,
]
);
foreach ($robots as $robot) {
echo $robot["year"], PHP_EOL;
}
~~~
## 自動生成標識列(Auto-generated identity columns)
Some models may have identity columns. These columns usually are the primary key of the mapped table.[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)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](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)is able to recognize the identity column. Depending on the database system, those columns may be serial columns like in PostgreSQL or auto\_increment columns in the case of MySQL.
PostgreSQL uses sequences to generate auto-numeric values, by default, Phalcon tries to obtain the generated value from the sequence “table\_field\_seq”, for example: robots\_id\_seq, if that sequence has a different name, the`getSequenceName()`method needs to be implemented:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function getSequenceName()
{
return "robots_sequence_name";
}
}
~~~
## 忽略指定列的數據(Skipping Columns)
To tell[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)that always omits some fields in the creation and/or update of records in order to delegate the database system the assignation of the values by a trigger or a default:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
// Skips fields/columns on both INSERT/UPDATE operations
$this->skipAttributes(
[
"year",
"price",
]
);
// Skips only when inserting
$this->skipAttributesOnCreate(
[
"created_at",
]
);
// Skips only when updating
$this->skipAttributesOnUpdate(
[
"modified_in",
]
);
}
}
~~~
This will ignore globally these fields on each INSERT/UPDATE operation on the whole application. If you want to ignore different attributes on different INSERT/UPDATE operations, you can specify the second parameter (boolean) - true for replacement. Forcing a default value can be done in the following way:
~~~
<?php
use Store\Toys\Robots;
use Phalcon\Db\RawValue;
$robot = new Robots();
$robot->name = "Bender";
$robot->year = 1999;
$robot->created_at = new RawValue("default");
$robot->create();
~~~
A callback also can be used to create a conditional assignment of automatic default values:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
use Phalcon\Db\RawValue;
class Robots extends Model
{
public function beforeCreate()
{
if ($this->price > 10000) {
$this->type = new RawValue("default");
}
}
}
~~~
> Never use a[Phalcon\\Db\\RawValue](http://docs.iphalcon.cn/api/Phalcon_Db_RawValue.html)to assign external data (such as user input) or variable data. The value of these fields is ignored when binding parameters to the query. So it could be used to attack the application injecting SQL.
### 動態更新(Dynamic Update)
SQL UPDATE statements are by default created with every column defined in the model (full all-field SQL update). You can change specific models to make dynamic updates, in this case, just the fields that had changed are used to create the final SQL statement.
In some cases this could improve the performance by reducing the traffic between the application and the database server, this specially helps when the table has blob/text fields:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->useDynamicUpdate(true);
}
}
~~~
## 獨立的列映射(Independent Column Mapping)
The ORM supports an independent column map, which allows the developer to use different column names in the model to the ones in the table. Phalcon will recognize the new column names and will rename them accordingly to match the respective columns in the database. This is a great feature when one needs to rename fields in the database without having to worry about all the queries in the code. A change in the column map in the model will take care of the rest. For example:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public $code;
public $theName;
public $theType;
public $theYear;
public function columnMap()
{
// Keys are the real names in the table and
// the values their names in the application
return [
"id" => "code",
"the_name" => "theName",
"the_type" => "theType",
"the_year" => "theYear",
];
}
}
~~~
Then you can use the new names naturally in your code:
~~~
<?php
use Store\Toys\Robots;
// Find a robot by its name
$robot = Robots::findFirst(
"theName = 'Voltron'"
);
echo $robot->theName, "\n";
// Get robots ordered by type
$robot = Robots::find(
[
"order" => "theType DESC",
]
);
foreach ($robots as $robot) {
echo "Code: ", $robot->code, "\n";
}
// Create a robot
$robot = new Robots();
$robot->code = "10101";
$robot->theName = "Bender";
$robot->theType = "Industrial";
$robot->theYear = 2999;
$robot->save();
~~~
Take into consideration the following the next when renaming your columns:
* References to attributes in relationships/validators must use the new names
* Refer the real column names will result in an exception by the ORM
The independent column map allow you to:
* Write applications using your own conventions
* Eliminate vendor prefixes/suffixes in your code
* Change column names without change your application code
## 記錄快照(Record Snapshots)
Specific models could be set to maintain a record snapshot when they’re queried. You can use this feature to implement auditing or just to know what fields are changed according to the data queried from the persistence:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->keepSnapshots(true);
}
}
~~~
When activating this feature the application consumes a bit more of memory to keep track of the original values obtained from the persistence. In models that have this feature activated you can check what fields changed:
~~~
<?php
use Store\Toys\Robots;
// Get a record from the database
$robot = Robots::findFirst();
// Change a column
$robot->name = "Other name";
var_dump($robot->getChangedFields()); // ["name"]
var_dump($robot->hasChanged("name")); // true
var_dump($robot->hasChanged("type")); // false
~~~
## 設置模式(Pointing to a different schema)
如果一個模型映射到一個在非默認的schemas/數據庫中的表,你可以通過`setSchema()`方法去定義它:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setSchema("toys");
}
}
~~~
## 設置多個數據庫(Setting multiple databases)
在Phalcon中,所有模型可以屬于同一個數據庫連接,也可以分屬獨立的數據庫連接。實際上,當[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/api/Phalcon_Mvc_Model.html)需要連接數據庫的時候,它在應用服務容器內請求”db”這個服務。 可以通過在`initialize()`方法內重寫這個服務的設置。
~~~
<?php
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
use Phalcon\Db\Adapter\Pdo\PostgreSQL as PostgreSQLPdo;
// This service returns a MySQL database
$di->set(
"dbMysql",
function () {
return new MysqlPdo(
[
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo",
]
);
}
);
// This service returns a PostgreSQL database
$di->set(
"dbPostgres",
function () {
return new PostgreSQLPdo(
[
"host" => "localhost",
"username" => "postgres",
"password" => "",
"dbname" => "invo",
]
);
}
);
~~~
然后,在`initialize()`方法內,我們為這個模型定義數據庫連接。
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setConnectionService("dbPostgres");
}
}
~~~
另外Phalcon還提供了更多的靈活性,你可分別定義用來讀取和寫入的數據庫連接。這對實現主從架構的數據庫負載均衡非常有用。 (譯者注:EvaEngine項目為使用Phalcon提供了更多的靈活性,推薦了解和使用)
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->setReadConnectionService("dbSlave");
$this->setWriteConnectionService("dbMaster");
}
}
~~~
另外ORM還可以通過根據當前查詢條件來實現一個 ‘shard’ 選擇器,來實現水平切分的功能。
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
/**
* Dynamically selects a shard
*
* @param array $intermediate
* @param array $bindParams
* @param array $bindTypes
*/
public function selectReadConnection($intermediate, $bindParams, $bindTypes)
{
// Check if there is a 'where' clause in the select
if (isset($intermediate["where"])) {
$conditions = $intermediate["where"];
// Choose the possible shard according to the conditions
if ($conditions["left"]["name"] === "id") {
$id = $conditions["right"]["value"];
if ($id > 0 && $id < 10000) {
return $this->getDI()->get("dbShard1");
}
if ($id > 10000) {
return $this->getDI()->get("dbShard2");
}
}
}
// Use a default shard
return $this->getDI()->get("dbShard0");
}
}
~~~
`selectReadConnection()`方法用來選擇正確的數據庫連接,這個方法攔截任何新的查詢操作:
~~~
<?php
use Store\Toys\Robots;
$robot = Robots::findFirst('id = 101');
~~~
## 注入服務到模型(Injecting services into Models)
你可能需要在模型中用到應用中注入的服務,下面的例子會教你如何去做:
~~~
<?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function notSaved()
{
// Obtain the flash service from the DI container
$flash = $this->getDI()->getFlash();
$messages = $this->getMessages();
// Show validation messages
foreach ($messages as $message) {
$flash->error($message);
}
}
}
~~~
每當 “create” 或者 “update” 操作失敗時會觸發 “notSave” 事件。所以我們從DI中獲取 “flash” 服務并推送確認消息。這樣的話,我們不需要每次在save之后去打印信息。
## 禁用或啟用特性(Disabling/Enabling Features)
In the ORM we have implemented a mechanism that allow you to enable/disable specific features or options globally on the fly. According to how you use the ORM you can disable that you aren’t using. These options can also be temporarily disabled if required:
~~~
<?php
use Phalcon\Mvc\Model;
Model::setup(
[
"events" => false,
"columnRenaming" => false,
]
);
~~~
The available options are:
| Option | Description | Default |
| --- | --- | --- |
| events | Enables/Disables callbacks, hooks and event notifications from all the models | `true` |
| columnRenaming | Enables/Disables the column renaming | `true` |
| notNullValidations | The ORM automatically validate the not null columns present in the mapped table | `true` |
| virtualForeignKeys | Enables/Disables the virtual foreign keys | `true` |
| phqlLiterals | Enables/Disables literals in the PHQL parser | `true` |
| lateStateBinding | Enables/Disables late state binding of the`Mvc\Model::cloneResultMap()`method | `false` |
## 獨立的組件(Stand-Alone component)
Using[Phalcon\\Mvc\\Model](http://docs.iphalcon.cn/reference/models.html)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();
~~~
- 簡介
- 安裝
- 安裝(installlation)
- XAMPP下的安裝
- WAMP下安裝
- Nginx安裝說明
- Apache安裝說明
- Cherokee 安裝說明
- 使用 PHP 內置 web 服務器
- Phalcon 開發工具
- Linux 系統下使用 Phalcon 開發工具
- Mac OS X 系統下使用 Phalcon 開發工具
- Windows 系統下使用 Phalcon 開發工具
- 教程
- 教程 1:讓我們通過例子來學習
- 教程 2:INVO簡介
- 教程 3: 保護INVO
- 教程4: 使用CRUD
- 教程5: 定制INVO
- 教程 6: V?kuró
- 教程 7:創建簡單的 REST API
- 組件
- 依賴注入與服務定位器
- MVC架構
- 使用控制器
- 使用模型
- 模型關系
- 事件與事件管理器
- Behaviors
- 模型元數據
- 事務管理
- 驗證數據完整性
- Workingwith Models
- Phalcon查詢語言
- 緩存對象關系映射
- 對象文檔映射 ODM
- 使用視圖
- 視圖助手
- 資源文件管理
- Volt 模版引擎
- MVC 應用
- 路由
- 調度控制器
- Micro Applications
- 使用命名空間
- 事件管理器
- Request Environmen
- 返回響應
- Cookie 管理
- 生成 URL 和 路徑
- 閃存消息
- 使用 Session 存儲數據
- 過濾與清理
- 上下文編碼
- 驗證Validation
- 表單_Forms
- 讀取配置
- 分頁 Pagination
- 使用緩存提高性能
- 安全
- 加密與解密 Encryption/Decryption
- 訪問控制列表
- 多語言支持
- 類加載器 Class Autoloader
- 日志記錄_Logging
- 注釋解析器 Annotations Parser
- 命令行應用 Command Line Applications
- Images
- 隊列 Queueing
- 數據庫抽象層
- 國際化
- 數據庫遷移
- 調試應用程序
- 單元測試
- 進階技巧與延伸閱讀
- 提高性能:下一步該做什么?
- Dependency Injection Explained
- Understanding How Phalcon Applications Work
- Api
- Abstract class Phalcon\Acl