內容目录上一个主题下一个主题 |
Validating Models¶验证数据完整性(Validating Data Integrity)¶Phalcon\Mvc\Model provides several events to validate data and implement business rules. The special “validation” event allows us to call built-in validators over the record. Phalcon exposes a few built-in validators that can be used at this stage of validation. The following example shows how to use it: <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
use Phalcon\Validation\Validator\InclusionIn;
class Robots extends Model
{
public function validation()
{
$validator = new Validation();
$validator->add(
"type",
new InclusionIn(
[
"domain" => [
"Mechanical",
"Virtual",
]
]
)
);
$validator->add(
"name",
new Uniqueness(
[
"message" => "The robot name must be unique",
]
)
);
return $this->validate($validator);
}
}
The above example performs a validation using the built-in validator “InclusionIn”. It checks the value of the field “type” in a domain list. If the value is not included in the method then the validator will fail and return false.
The idea of creating validators is make them reusable between several models. A validator can also be as simple as: <?php
namespace Store\Toys;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Message;
class Robots extends Model
{
public function validation()
{
if ($this->type === "Old") {
$message = new Message(
"Sorry, old robots are not allowed anymore",
"type",
"MyType"
);
$this->appendMessage($message);
return false;
}
return true;
}
}
验证信息(Validation Messages)¶Phalcon\Mvc\Model has a messaging subsystem that provides a flexible way to output or store the validation messages generated during the insert/update processes. Each message is an instance of Phalcon\Mvc\Model\Message and the set of
messages generated can be retrieved with the <?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;
}
}
验证失败事件(Validation Failed Events)¶Another type of events are available when the data validation process finds any inconsistency:
|