Home >Backend Development >PHP Tutorial >Symfony data verification method example analysis, symfony example analysis_PHP tutorial
The examples in this article describe the Symfony data verification method. Share it with everyone for your reference. The specific analysis is as follows:
Validation is a common task in web applications. Data entered into the form needs to be validated. Data also needs to be verified before being written to the database or when passed to a webservice.
Symfony2 is equipped with a Validator component, which makes the verification work simple and easy to understand. This component is based on the JSR303 Bean validation specification. A Java specification for use in PHP.
Basic Verification
The best way to understand validation is to see how it performs. First, assume that you have created a PHP object that is used somewhere in your application.
class Author
{
Public $name;
}
Up to now, it's just a normal class that serves some purpose in your application. The purpose of verification is to tell you whether the object's data is legal. For this purpose, you need to configure an object to follow a list of rules or constraints to make its data legal. These rules can be described in many different formats (eg, YAML, XML, class declarations or PHP). For example, we ensure that the attribute $name cannot be empty, so add the following rule:
YAML format:
class Author
{
/**
* @AssertNotBlank()
*/
Public $name;
}
XML format:
PHP code format:
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsNotBlank;
class Author
{
Public $name;
Public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('name', new NotBlank());
}
}
Protected and private attributes and getter methods can also be verified.
Use validator service:
Next, use the validate method of the validator service to actually verify the Author object. The validator's job is simple: read the constraint rules of a class to verify whether the data of an object conforms to these rule constraints. If validation fails, an error array will be returned. Now we execute it in a controller:
public function indexAction()
{
$author = new Author();
//... What to do with the $auother object
$validator = $this->get('validator');
$errors = $validator->validate($author);
if(count($errors) >0){
Return new Response(print_r($errors, true));
}else{
Return new Response('The author is valid! Yes!');
}
}
If the $name attribute is empty, you will see the following error message:
AcmeBlogBundleAuthor.name:
This value should not be blank
If you insert a value for the $name attribute, you will get a happy success message.
Most of the time, you don't need to communicate directly with the validator service or worry about printing errors at all.
Most of the time, you will use validation indirectly when processing submitted form data.
You can also pass a collection of error messages to a template:
In the template, you can output the error list as accurately as you need:
Twig format:
Checksum form
The validator service can be used to verify any object at any time. In fact, you will often use validators indirectly when processing forms. Symfony's form library indirectly uses the validator service to validate the underlying objects after the data has been submitted and bound. Object constraint violation information will be converted to a FieldError object, which can be easily displayed in your form. The traditional form submission process in a controller is as follows:
public function updateAction(Request $request)
{
$author = new AcmeBlogBundleEntityAuthor();
$form = $this->createForm(new AuthorType(),$author);
if($request->getMethod() =='POST'){
$form->bindRequest($request);
If($form->isvalid()){
//Do some operations on $author
return $this->redirect($this->generateUrl('...'));
}
}
return $this->render('BlogBundle:Author:form.html.twig',array(
'form' => $form->createView(),
));
}
Configuration:
Symfony2 validator is available by default. But if you use the life method to specify your constraints, then you need to explicitly enable the declaration function:
YAML format:
Constraint rules
Validator is designed to verify objects according to constraint rules. To validate an object, just map one or more constraints to the class it is validating and pass it to the validator service.
Essentially, a constraint is a simple PHP object that generates a decision statement. In real life, a constraint can be a rule constraint such as "the cake cannot be burnt". In Symfony2, constraints are all the same: they determine whether a certain condition is true. Given a value, the constraint tells you whether the value obeys your constraint rules.
Constraint rules supported by Symfony2
First are the basic constraint rules: use them to decide very basic things, like the value of your object's properties or the return value of a method.
NotBlank, Blank, NotNull, Null, True, False, Type
String constraints: Email, MinLength, MaxLength, Url, Regex, Ip, etc.
Numerical constraints: Max, Min
Date constraints: Date, DateTime and Time
Collection constraints: Choice, Collection, UniqueEntity, Language, Locale and Country, etc.
File constraints: File,Image
Other constraints: Callback, All, Valid
You can also create your own custom constraints.
Constraint configuration:
Some constraints, such as NotBlank, are very simple, but others, such as Choice constraints, have many configuration items that need to be set. Assuming that the Author class has another attribute, gener can be set to "male" or "female":
YAML format:
class Author
{
/**
* @AssertChoice(
* choices = {"male","female"},
* message = "Choose a valid gender."
* )
*/
Public $gender;
}
XML format:
in
& Lt; option name = "Message" & gt; Choose a valid gender. & Lt;/option & gt;
PHP code format:
Copy code
class Author
{
Public $gender;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Choice(array(
'choices' => array('male', 'female'),
'message' => 'Choose a valid gender.',
)));
}
}
A constraint’s options are usually passed through an array. Some constraints also allow you to pass a value. "default" is optional in arrays. When using Choice constraints, the choices option can be specified in this way.
YAML format:
class Author
{
/**
* @AssertChoice({"male", "female"})
*/
protected $gender;
}
XML format:
PHP format:
class Author
{
protected $gender;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('gender', new Choice(array('male', 'female')));
}
}
Constraint target
Constraints can be applied to a class property or a public getter method. Attribute constraints are the most commonly used and simplest, while public getter method constraints allow you to specify a complex constraint rule.
Attribute constraints:
The attributes of the verification class are one of the most common verification techniques. Symfony2 allows you to verify private, protected or public properties. The following code shows how to configure the $firstName property of the Author object to have at least 3 characters:
YAML format:
class Author
{
/**
* @AssertNotBlank()
* @AssertMinLength(3)
*/
Private $firstName;
}
XML format:
PHP code format:
class Author
{
Private $firstName;
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('firstName', new NotBlank());
$metadata->addPropertyConstraint('firstName', new MinLength(3));
}
}
Getters
Constraints can also be applied to the return value of a method. Symfony2 allows you to add a constraint to any public method that begins with "get" or "is". The benefit of this technique is that it allows you to dynamically validate your objects. For example, suppose you want to make sure that the password field does not match the user's first name (for security reasons). You can do this by creating an idPasswordLegal method and then determining that this method must return true:
YAML format:
class Author
{
/**
* @AssertTrue(message = "The password cannot match your first name")
*/
Public function isPasswordLegal()
{
// return true or false
}
}
XML format:
class Author
{
Public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addGetterConstraint('passwordLegal', new True(array(
'message' => 'The password cannot match your first name',
)));
}
}
Now we create an isPasswordLegal() method and include the logic you need:
Category:
Some constraints apply to the entire class being verified. For example, the Callback constraint is a general constraint that can be applied to the class itself. When a class is validated, the methods described by the constraints are simply executed so that each can provide a more personalized validation.
Check grouping
So far, you have been able to add constraints to a class and ask if the class passes in all the defined constraint rules. In some cases, you only need to verify an object using some of the rules of the class. To do this, you organize each constraint into one or more validation groups, and then the application uses one of the validation groups. For example, suppose you have a User class that is used when users register and when users update their contact information.
YAML format:
Class declaration format:
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentValidatorConstraints as Assert;
class User implements UserInterface
{
/**
* @AssertEmail(groups={"registration"})
*/
private $email;
/**
* @AssertNotBlank(groups={"registration"})
* @AssertMinLength(limit=7, groups={"registration"})
*/
private $password;
/**
* @AssertMinLength(2)
*/
private $city;
}
XML format:
PHP代码格式:
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsEmail;
use SymfonyComponentValidatorConstraintsNotBlank;
use SymfonyComponentValidatorConstraintsMinLength;
class User
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('email', new Email(array(
'groups' => array('registration')
)));
$metadata->addPropertyConstraint('password', new NotBlank(array(
'groups' => array('registration')
)));
$metadata->addPropertyConstraint('password', new MinLength(array(
'limit' => 7,
'groups' => array('registration')
)));
$metadata->addPropertyConstraint('city', new MinLength(3));
}
}
这里我们配置了两个校验组:
default默认组: 包括所有没有分配到任何组的约束规则
registration: 只包含了email和password字段的校验规则
告诉validator使用指定的校验组,传一个或者多个组名作为validate()方法的第二个参数即可:
Value and array validation
So far, we have looked at how to validate an entire object. But sometimes, we may want to verify a single value, such as verifying whether a string is a valid email address. This is very simple and is done in the Controller class as follows:
public function addEmailAction($email)
{
$emailConstraint = new Email();
// All verification options can be set like this
$emailConstraint->message = 'Invalid email address';
// Use validator to verify a value
$errorList = $this->get('validator')->validateValue($email, $emailConstraint);
if (count($errorList) == 0) {
// This is a legitimate email address, what can be done
} else {
// This is an illegal email address
$errorMessage = $errorList[0]->getMessage()
// Do some error handling
}
// ...
}
By calling the validateValue method of the validator, you can pass in a raw value and a verification object you want to use. This method returns a ConstraintViolationList object, which only plays the role of an array of error messages. Each error in the collection is a ConstraintViolation object, and the error information can be obtained using the object's getMessage method.
Summary:
Symfony2’s validator is a powerful tool that can be used to ensure the validity of any object data. Its power comes from the constraint rules you can apply to your object's properties and getter methods. In fact, most of the time you use the validation framework indirectly when using forms. Remember that it can be applied to validate any object anywhere.
I hope this article will be helpful to everyone’s Symfony framework programming.