自最新版本的Phalcon发布以来,文档中提供的示例似乎无法正常工作。
首先,我使用phalcon model User
在命令行创建一个DevTools的新模型。
然后,我修改了validation()
函数。我的models\User.php
文件:
use Phalcon\Mvc\Model\Validator\Email as Email;
use Phalcon\Mvc\Model\Validator\Uniqueness as Uniqueness;
use Phalcon\Mvc\Model\Validator\StringLength as StringLength;
class User extends \Phalcon\Mvc\Model
{
public function validation()
{
$this->validate(
new Email(
array(
'field' => 'email',
'message' => 'Please enter a valid email'
)
)
);
$this->validate(
new Uniqueness(
array(
'field' => 'email',
'message' => 'Your email is already in use'
)
)
);
$this->validate(
new StringLength(
array(
'field' => 'password',
'min' => 4,
'max' => 30,
'minMessage' => 'Your password must be at least 4 characters',
'maxMessage' => 'Your password must be less than 30 characters'
)
)
);
if ($this->validationHasFailed() == true) {
return false;
}
return true;
}
}
但是,这会引发以下错误:
可捕获致命错误:参数1传递给Phalcon \ Mvc \ Model :: validate()必须实现接口Phalcon \ ValidationInterface,Phalcon \ Mvc \ Model \ Validator \ Email实例 C:\ xampp \ htdocs \ app \ models \ User.php 在线 27
这是什么意思?我相信Phalcon\Validation
和Phalcon\Mvc\Model\Validator
是完全不同的野兽(后者提供更多功能)?
答案 0 :(得分:11)
截至Phalcon 3.0 Phalcon\Mvc\Model\Validation
现已弃用,Phalcon\Validation
。这样做是为了减少代码库,因为两个组件都在做类似的工作。您可以在下面找到需要更改的示例。
namespace Invo\Models;
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Validator\Email as EmailValidator;
use Phalcon\Mvc\Model\Validator\Uniqueness as UniquenessValidator;
class Users extends Model
{
public function validation()
{
$this->validate(
new EmailValidator(
[
'field' => 'email',
]
)
);
$this->validate(
new UniquenessValidator(
[
'field' => 'username',
'message' => 'Sorry, That username is already taken',
]
)
);
if ($this->validationHasFailed() == true) {
return false;
}
}
}
namespace Invo\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Email as EmailValidator;
use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator;
class Users extends Model
{
public function validation()
{
$validator = new Validation();
$validator->add(
'email', //your field name
new EmailValidator([
'model' => $this,
'message' => 'Please enter a correct email address'
])
);
$validator->add(
'username',
new UniquenessValidator([
'model' => $this,
'message' => 'Sorry, That username is already taken',
])
);
return $this->validate($validator);
}
}
可以在the Blog中找到更多信息和补丁说明。