Analysis of Symfony data checking method

Source: Internet
Author: User
Tags valid email address
This article uses the example to analyze the Symfony data check method, here to share for the reference, the interested small partner may look


Validation is a common task in a Web application. The data entered into the form needs to be verified. The data also needs to be validated before being written to the database or passing in a webservice.

The Symfony2 is equipped with a validator component that makes the verification process easy to understand. The component is based on the JSR303 Bean checksum specification. A Java specification is used in PHP.

Basic validation

The best way to understand the checksum is to see how it behaves. First, let's say you've created a PHP object for your application somewhere.

The code is as follows:

Src/acme/blogbundle/entity/author.phpnamespace acme\blogbundle\entity;class author{public $name;}


So far, it's just a generic class that serves some purpose for your application. And the purpose of the check is to tell you whether the data of the object is legitimate. For this purpose, you need to configure an object to conform to the rules or constraints list to make its own data legitimate. These rules can be described in a number of different formats (for example, Yaml,xml, class declarations, or PHP). For example, we guarantee that the attribute $name cannot be empty to add the following rule:

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\author:properties:name:-NotBlank: ~


class declaration format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse symfony\component\validator\constraints as Assert;class Author{/*** @ Assert\notblank () */public $name;}

XML format:

The code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><constraint-mapping xmlns= "http://symfony.com/schema/dic/ Constraint-mapping "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://symfony.com /schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd ">

PHP Code format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse Symfony\component\validator\mapping\classmetadata;use Symfony\ Component\validator\constraints\notblank;class author{public $name;p ublic static function Loadvalidatormetadata ( Classmetadata $metadata) {$metadata->addpropertyconstraint (' name ', New Notblank ())}}

The protected and private properties, as well as getter methods, can also be verified.

Using the Validator service:

Next, use the Validate method of the validator service to really validate the author object. Validator's work is simple: Read the constraint rules of a class to verify that the data for an object conforms to these rule constraints. If the checksum fails, an array of errors is returned. Now we're going to execute it in a controller:

The code is as follows:

Use Symfony\component\httpfoundation\response;use acme\blogbundle\entity\author;//...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 property is empty, you will see the following error message:

Acme\blogbundle\author.name:
This value should not being 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 need to worry about printing errors at all.

In most cases, you will use the check when processing the submission form data time.

You can also pass a set of error messages to a template:

The code is as follows:

if (count ($errors) >0) {return $this->render (' AcmeBlogBundle:Author:validate.html.twig ', Array (' Errors ' = $ errors,));} else{//...}


In the template, you can accurately output the error list as needed:

Twig format:

The code is as follows:

{# Src/acme/blogbundle/resources/views/author/validate.html.twig #} The author have the following errros{% for error in errors%}{{error.message}}{% endfor%}

Validation and form

The validator service can be used to validate any object at any time. In fact, you will often use validator indirectly when working with forms. Symfony's Form class libraries use the validator service indirectly to validate the underlying objects after data is committed and bound. Object violation constraint information will be converted to the Fielderror object, which can easily be displayed in your form. The traditional form submission process in a controller is as follows:

The code is as follows:

Use Acme\blogbundle\entity\author;use acme\blogbundle\form\authortype;use acme\component\httpfoundation\request;/ /...public function updateaction (Request $request) {$author = new Acme\blogbundle\entity\author (); $form = $this CreateForm (New Authortype (), $author), if ($request->getmethod () = = ' POST ') {$form->bindrequest ($request); 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 turn on declarative functionality:

YAML format:

The code is as follows:

# app/config/config.ymlframework:validation: {enable_annotations:true}

XML format:

The code is as follows:





PHP Code format:

The code is as follows:

App/config/config.php$contianer->loadfromextension (' framework ', array (' validation ' = = Array (' Enable_ Annotations ' =>true,)));

Constraint rules

Validator is designed to validate objects in accordance with constraint rules. To validate an object, you only need to 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 can generate a decision statement. In real life, a constraint can be a rule that "cakes cannot be burnt." In Symfony2, the constraints are similar: They decide whether a condition is true or not. Given a value, the constraint tells you whether the value adheres to your constraint rules.

SYMFONY2 supported constraint rules

The first is the underlying constraint rule: Use them to decide very basic things, such as the value of your object's properties or the return value of the method.

Notblank,blank,notnull,null,true,false,type

String constraints: EMAIL,MINLENGTH,MAXLENGTH,URL,REGEX,IP, etc.
Number constraint: Max,min
Date constraint: Date,datetime and time

Set constraints: Choice,collection,uniqueentity,language,locale, country, and so on.
File constraint: File,image
Other constraints: Callback,all,valid

You can create your own custom constraints as well.

Constraint configuration:

Some constraints, such as Notblank, are simple, but others, such as choice constraints, have many configuration items that need to be set. Assuming that the author class has another attribute, the Gener can be set to "male" or "female":

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\author:properties:gener:-Choice: { Choices: [Male, female], message:choos a valid gender. }


class declaration format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse symfony\component\validator\constraints as Assert;class Author{/*** @ Assert\choice (* choices = {"Male", "female"},* message = "Choose a valid gender.") *) */public $gender;}


XML format:

The code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><constraint-mapping xmlns= "http://symfony.com/schema/dic/ Constraint-mapping "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://symfony.com /schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd ">

PHP Code format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse Symfony\component\validator\mapping\classmetadata;use Symfony\ Component\validator\constraints\notblank;class author{public $gender;p ublic static function Loadvalidatormetadata ( Classmetadata $metadata) {$metadata->addpropertyconstraint (' Gender ', new Choice (' choices ' = Array (' Male ', ' female '), ' message ' = ' Choose a valid gender. ', '));}}

An option for a constraint is usually passed through an array. Some constraints also allow you to pass a value. "Default" is optional in the array. The choices option can be specified in this way when choice constraints.

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\author:properties:gender:-Choice: [ Male, female]

class declaration format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse symfony\component\validator\constraints as Assert;class Author{/*** @ Assert\choice ({"Male", "female"}) */protected $gender;}

XML format:

The code is as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><constraint-mapping xmlns= "http://symfony.com/schema/dic/ Constraint-mapping "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://symfony.com /schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd "> Malefemale

PHP Format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse Symfony\component\validator\mapping\classmetadata;use Symfony\ Component\validator\constraints\choice;class author{protected $gender;p ublic static function Loadvalidatormetadata ( Classmetadata $metadata) {$metadata->addpropertyconstraint (' Gender ', New Choice (Array (' Male ', ' Female '))}}


Constraint target

Constraints can be used for properties of a class or for a public getter method. Property constraints are the most common and simplest, and public getter method constraints allow you to specify a complex constraint rule.

Attribute constraints:

Check the properties of a class the most common calibration technique. Symfony2 allows you to verify the private,protected or public properties. The following code shows how to configure the author object's $firstname property to have at least 3 characters:

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\author:properties:firstname:- Notblank: ~-minlength:3


class declaration format:

The code is as follows:

Acme/blogbundle/entity/author.phpuse symfony\component\validator\constraints as Assert;class Author{/*** @Assert \ Notblank () * @Assert \minlength (3) */private $firstName;}


XML format:

The code is as follows:





3


PHP Code format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse Symfony\component\validator\mapping\classmetadata;use Symfony\ Component\validator\constraints\notblank;use Symfony\component\validator\constraints\minlength;class Author{ Private $firstName;p ublic 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 public method that constrains the beginning of any "get" or "is". The advantage of this technique is that you are allowed to validate your objects dynamically. For example, suppose you want to confirm that the password field does not match the user's first name (for security reasons). You can do this by creating a Idpasswordlegal method and then deciding that this method must return true:

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\author:getters:passwordlegal:-"True ": {message:" The password cannot match your first name "}

class declaration format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse symfony\component\validator\constraints as Assert;class Author{/*** @ Assert\true (message = "The password cannot match your first name") */public function Ispasswordlegal () {//return True or FA LSE}}


XML format:

The code is as follows:


PHP Code format:

The code is as follows:

Src/acme/blogbundle/entity/author.phpuse Symfony\component\validator\mapping\classmetadata;use Symfony\ Component\validator\constraints\true;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 a Ispasswordlegal () method and contain the logic you need:

The code is as follows:

Public Function Ispasswordlegal () {return ($this->firstname! = $this->password);}

Sharp-eyed might notice that the getter prefix ("Get" or "is") was ignored at the time of mapping. This allows you to move a constraint to a property with the same name and vice versa without changing the validation rules.


Class:

Some constraints apply to the entire class being verified above. For example, the callback constraint is a generic constraint that can be applied to the class itself. When the class is validated, the method being constrained is simply executed so that each one can provide a more personalized check.

Check grouping

So far, you've been able to add constraints to the class and ask if the class passed in all defined constraint rules. In some cases, you only need to use some of the rules of the class to validate an object. To do this, you can organize each constraint into one or more validation groups, and then the app uses one of the set of checksums. For example, suppose you have a user class that will be used when users register and users update their contact information.

YAML format:

The code is as follows:

# src/acme/blogbundle/resources/config/validation.ymlacme\blogbundle\entity\user:properties:email:-Email: { Groups: [registration]}password:-Notblank: {groups: [registration]}-MinLength: {limit:7, Groups: [registration]}ci ty:-Minlength:2


class declaration format:

The code is as follows:

Src/acme/blogbundle/entity/user.phpnamespace Acme\blogbundle\entity;use Symfony\component\security\core\user\ Userinterface;use symfony\component\validator\constraints as Assert;class User implements userinterface{/*** @Assert \ Email (groups={"Registration"}) */private $email/*** @Assert \notblank (groups={"Registration"}) * @Assert \minlength ( limit=7, groups={"Registration"}) */private $password/*** @Assert \minlength (2) */private $city;}

XML format:

The code is as follows:

7

PHP Code format:

The code is as follows:

Src/acme/blogbundle/entity/user.phpnamespace Acme\blogbundle\entity;use symfony\component\validator\mapping\ Classmetadata;use Symfony\component\validator\constraints\email;use symfony\component\validator\constraints\ Notblank;use symfony\component\validator\constraints\minlength;class user{public static function Loadvalidatormetadata (Classmetadata $metadata) {$metadata->addpropertyconstraint (' email ', new email (' Groups ' = = Array (' registration '))); $metadata->addpropertyconstraint (' Password ', new Notblank (' groups ') = = Array (' registration '))), $metadata->addpropertyconstraint (' Password ', new MinLength (Array (' limit ' = 7, ' groups ' = = Array (' registration ')), $metadata->addpropertyconstraint (' City ', New MinLength (3));}}

Here we have configured two check groups:
Default defaults group: Includes all constraint rules that are not assigned to any group
Registration: Contains only the validation rules for email and password fields

Tells validator to use the specified validation group to pass one or more group names as the second parameter of the Validate () method:

The code is as follows:

$errors = $validator->validate ($author, Array (' registration '));

Value and Array checksum

So far, we've seen how to verify the entire object. But sometimes, we might want to check for a single value, such as verifying that a string is not a valid email address. This is very simple and is done in the Controller class as follows:

The code is as follows:

Reference the appropriate checksum namespace before the Controller class use Symfony\component\validator\constraints\email;public function Addemailaction ($email {$emailConstraint = new email ();//All Calibration options (options) can be set $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 Validator's Validatevalue method, you can pass in a raw value and a checksum object that you want to use. The method returns a Constraintviolationlist object that acts as a role in an array of error messages only. Each error in the collection is a Constraintviolation object that uses the object's GetMessage method to get the error message.

Summarize:

Symfony2 's validator is a powerful tool that can be used to guarantee the legitimacy of any object data. Its power comes from constraint rules, and you can apply them to your object's properties and Getter methods. In fact, most of the time when you use a form, the validation framework is applied indirectly, remembering that it can be used to validate any object anywhere.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.