Example Analysis _php example of symfony data check method

Source: Internet
Author: User
Tags valid email address
This paper describes the Symfony data verification method. Share to everyone for your reference. The specific analysis is as follows:

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.
Copy the Code code as follows://src/acme/blogbundle/entity/author.php
namespace 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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\author:
Properties
Name
-Notblank: ~
class declaration format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use symfony\component\validator\constraints as Assert;

Class Author
{
/**
* @Assert \notblank ()
*/
Public $name;
}

XML format:
Copy the Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>

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:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php

Use Symfony\component\validator\mapping\classmetadata;
Use Symfony\component\validator\constraints\notblank;

Class Author
{
Public $name;

public 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:
Copy the Code Code as follows: Use Symfony\component\httpfoundation\response;
Use Acme\blogbundle\entity\author;
//...

Public Function indexaction ()
{
$author = new author ();
//... What to do with $auother objects

$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:
Copy the Code code 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:
Copy the Code Code as follows: {# Src/acme/blogbundle/resources/views/author/validate.html.twig #}

The author has 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:
Copy the Code Code 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);

if ($form->isvalid ()) {
Do some work 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:
Copy the Code code as follows: # APP/CONFIG/CONFIG.YML
Framework
Validation: {enable_annotations:true}
XML format:
Copy the Code code as follows:



PHP Code format:
Copy the Code Code 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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\author:
Properties
Gener:
-Choice: {choices: [male, female], message:choos a valid gender.}
class declaration format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use symfony\component\validator\constraints as Assert;

Class Author
{
/**
* @Assert \choice (
* choices = {"Male", "female"},
* message = "Choose a valid gender."
* )
*/
Public $gender;
}

XML format:
Copy the Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>

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 ">





Male
Female

Choose a valid gender.



PHP Code format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use Symfony\component\validator\mapping\classmetadata;
Use Symfony\component\validator\constraints\notblank;

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. ',
)));
}
}

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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\author:
Properties
Gender
-Choice: [Male, female]
class declaration format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use symfony\component\validator\constraints as Assert;

Class Author
{
/**
* @Assert \choice ({"Male", "female"})
*/
protected $gender;
}

XML format:
Copy the Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>

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 ">




Male
Female



PHP Format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use Symfony\component\validator\mapping\classmetadata;
Use Symfony\component\validator\constraints\choice;

Class Author
{
protected $gender;

public 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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\author:
Properties
FirstName:
-Notblank: ~
-Minlength:3
class declaration format:
Copy the Code Code as follows://acme/blogbundle/entity/author.php
Use symfony\component\validator\constraints as Assert;

Class Author
{
/**
* @Assert \notblank ()
* @Assert \minlength (3)
*/
Private $firstName;
}

XML format:
Copy the Code code as follows:



3

PHP Code format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use Symfony\component\validator\mapping\classmetadata;
Use Symfony\component\validator\constraints\notblank;
Use Symfony\component\validator\constraints\minlength;

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 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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\author:
Getters
Passwordlegal:
-"True": {message: "The password cannot match your first name"}
class declaration format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use symfony\component\validator\constraints as Assert;

Class Author
{
/**
* @Assert \true (message = "The password cannot match your first name")
*/
Public Function Ispasswordlegal ()
{
return TRUE or False
}
}

XML format:
Copy the Code code as follows:



The password cannot match your first name


PHP Code format:
Copy the Code Code as follows://src/acme/blogbundle/entity/author.php
Use 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:
Copy the Code Code 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:
Copy the Code code as follows: # SRC/ACME/BLOGBUNDLE/RESOURCES/CONFIG/VALIDATION.YML
Acme\blogbundle\entity\user:
Properties
Email
-Email: {groups: [registration]}
Password
-Notblank: {groups: [registration]}
-MinLength: {limit:7, Groups: [Registration]}
City
-Minlength:2

class declaration format:
Copy the Code Code as follows://src/acme/blogbundle/entity/user.php
namespace 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:
Copy code code as follows:!--src/acme/blogbundle/resources/config/validation.xml-->
Class Name= "Acme\blogbundle\entity\user" >



registration






registration



7

registration




7

PHP Code format:
Copy the Code Code as follows://src/acme/blogbundle/entity/user.php
namespace 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 (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));
}
}

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:
Copy the code 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:
Copy the code as follows://reference the appropriate check namespace before the Controller class
Use Symfony\component\validator\constraints\email;

Public Function addemailaction ($email)
{
$emailConstraint = new Email ();
All calibration 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 you can do
} 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.

It is hoped that this article will be helpful to everyone's symfony framework design.

  • 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.