這里繼續(xù)窺探 symfony/form 的用法, 來(lái)了解一下 Form 的 Validator.
通常在項(xiàng)目開(kāi)發(fā)中, 框架自帶的表單驗(yàn)證器可以滿(mǎn)足硬性指標(biāo), 但是業(yè)務(wù)驗(yàn)證部分就無(wú)能為力了. 需要工程師自行開(kāi)發(fā)適合項(xiàng)目的表單驗(yàn)證規(guī)則.
比如在用戶(hù)系統(tǒng)中, 用戶(hù)的郵件地址我們需要進(jìn)行唯一性驗(yàn)證, 已經(jīng)被注冊(cè)的郵件地址不能重復(fù)注冊(cè), 那么我們就需要開(kāi)發(fā)一個(gè) EmailUniqueValidator 來(lái)添加到 Form 的 email 字段中的驗(yàn)證器中去.
繼續(xù)使用 make:validator 指令, 創(chuàng)建一個(gè)驗(yàn)證器: EmailUniqueValidator
$ bin/console make:validator
The name of the validator class (e.g. EnabledValidator):
> EmailUniqueValidator
created: src/Validator/EmailUniqueValidator.php
created: src/Validator/EmailUnique.php
Success!
Next: Open your new constraint & validators and add your logic.
修改 src/Validator/EmailUnique.php 因?yàn)槲覀冃枰獋魅霐?shù)據(jù)庫(kù)查詢(xún)管理器和配置錯(cuò)誤信息.
<?php
namespace App\Validator;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class EmailUnique extends Constraint
{
/**
* @var \Doctrine\ORM\EntityManager
*/
public $manager;
public $message = 'The email address is already in use.';
}
接下來(lái)實(shí)現(xiàn)正式的驗(yàn)證器代碼, 修改 src/Validator/EmailUniqueValidator.php
<?php
namespace App\Validator;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
class EmailUniqueValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof EmailUnique) {
throw new UnexpectedTypeException($constraint, EmailUnique::class);
}
if (!is_string($value)) {
throw new UnexpectedValueException($value, 'string');
}
if ($this->emailInUsed($value, $constraint->manager->getRepository(User::class))) {
$this->context->buildViolation($constraint->message)->addViolation();
}
}
/**
* 檢測(cè)郵件地址是否已經(jīng)存在數(shù)據(jù)庫(kù)中.
*
* @param string $email
* @param UserRepository $userRepository
* @return bool
*/
private function emailInUsed(string $email, UserRepository $userRepository): bool
{
//根據(jù)郵件地址查詢(xún)數(shù)據(jù)庫(kù)
$user = $userRepository->findOneBy(['email' => $email]);
if ($user instanceof User) {
return true;
}
return false;
}
}
接下來(lái)就剩下在 UserType 這個(gè) Form 類(lèi)中添加這個(gè)郵件地址驗(yàn)證器: EmailUnique, 再傳入數(shù)據(jù)庫(kù)管理器這個(gè)對(duì)象: Doctrine\Common\Persistence\ObjectManager.
ObjectManager 對(duì)象傳入到 Form 類(lèi)中通??梢酝ㄟ^(guò)創(chuàng)建是通過(guò)參數(shù)傳遞, 也可以把 Form 類(lèi)定義為 Service 來(lái)使用, 通過(guò)注入傳遞這個(gè) ObjectManager.
通過(guò)參數(shù)來(lái)傳遞到 UserType
<?php
namespace App\Form;
use App\Validator\EmailUnique;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/**
* @var \Doctrine\ORM\EntityManager $entityManager
*/
$entityManager = $options['entity_manager'];
$builder
->add('email', EmailType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Emaill address cannot be empty.']),
new Email(['message' => 'This email is not a valid email address.']),
new EmailUnique([
'manager' => $entityManager, // manager 與 EmailUniqueValidator 的 manager屬性保持同名.
]),
]
])
->add('passwd', PasswordType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Password cannot be empty character.']),
new Length([
'min' => 4,
'max' => 12,
'minMessage' => 'Your password must be at least {{ limit }} characters long',
'maxMessage' => 'Your password cannot be longer than {{ limit }} characters',
])
]
])
->add('name', TextType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Your name cannot be empty.']),
new Length([
'min' => 2,
'max' => 12,
'minMessage' => 'Your name must be at least {{ limit }} characters long',
'maxMessage' => 'Your name cannot be longer than {{ limit }} characters',
])
]
])
->add('save', SubmitType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
//表單創(chuàng)建時(shí)需要提供實(shí)體管理器參數(shù)
$resolver->setRequired('entity_manager');
}
}
在 Controller 中傳入 ObjectManager:
// ...
public function signUp(Request $request)
{
//創(chuàng)建用戶(hù)注冊(cè)表單對(duì)象
$form = $this->createForm(UserType::class, null, [
'entity_manager' => $this->getDoctrine()->getManager(),
]);
//監(jiān)聽(tīng)表單請(qǐng)求
$form->handleRequest($request);
// ...
這樣郵件唯一性驗(yàn)證就完成了.
如果修改 Controller 里的代碼, 把 UserType 定義成 Service, 也可以實(shí)現(xiàn)參數(shù)的注入.
修改 src/Form/UserType.php
<?php
namespace App\Form;
use App\Validator\EmailUnique;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class UserType extends AbstractType
{
/**
* @var \Doctrine\ORM\EntityManager
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Emaill address cannot be empty.']),
new Email(['message' => 'This email is not a valid email address.']),
new EmailUnique([
'manager' => $this->entityManager, // manager 與 EmailUniqueValidator 的 manager屬性保持同名.
]),
]
])
->add('passwd', PasswordType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Password cannot be empty character.']),
new Length([
'min' => 4,
'max' => 12,
'minMessage' => 'Your password must be at least {{ limit }} characters long',
'maxMessage' => 'Your password cannot be longer than {{ limit }} characters',
])
]
])
->add('name', TextType::class, [
'empty_data' => '',
'constraints' => [
new NotBlank(['message' => 'Your name cannot be empty.']),
new Length([
'min' => 2,
'max' => 12,
'minMessage' => 'Your name must be at least {{ limit }} characters long',
'maxMessage' => 'Your name cannot be longer than {{ limit }} characters',
])
]
])
->add('save', SubmitType::class)
;
}
}
把 Controller 里的代碼復(fù)原:
//...
//創(chuàng)建用戶(hù)注冊(cè)表單對(duì)象
$form = $this->createForm(UserType::class);
//監(jiān)聽(tīng)表單請(qǐng)求
$form->handleRequest($request);
//...
如此, 也實(shí)現(xiàn)了與上面同樣的功能. 這里由于使用了 autowire 功能. 不需要手動(dòng)注冊(cè) Service. 如果未啟動(dòng), 需要手動(dòng)修改一下 config/service.yaml 添加一下聲明:
services:
App\Form\UserType:
arguments: ['@doctrine.orm.entity_manager']
tags: [form.type]
到此, 簡(jiǎn)單的自定義 Valiadator 就完成了.