Symfony Data Verification Method Instance Analysis

Source: Internet
Author: User
This article mainly introduces the Symfony data verification method. The example analyzes common techniques and precautions for Symfony data verification, which has some reference value. For more information, see

This article mainly introduces the Symfony data verification method. The example analyzes common techniques and precautions for Symfony data verification, which has some reference value. For more information, see

This example describes the Symfony data verification method. Share it with you for your reference. The specific analysis is as follows:

Verification is a common task in web applications. Data input to the form needs to be verified. Data must also be verified before being written to the database or when a webservice is passed in.

Symfony2 is equipped with a Validator component, which makes the verification work easy to understand. This component is based on the JSR303 Bean validation specification. A Java specification is used in PHP.

Basic Verification

The best way to understand verification is to view its performance. First, assume that you have created a PHP Object for somewhere in your application.

The Code is as follows:

// Src/Acme/BlogBundle/Entity/Author. php
Namespace Acme \ BlogBundle \ Entity;

Class Author
{
Public $ name;
}

So far, it is just a common class that serves certain purposes of 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 comply with rules or constraints to make its data legal. These rules can be described in different formats (such as YAML, XML, class declaration, or PHP ). For example, to add the following rule, ensure that the attribute $ name cannot be blank:

YAML format:

The Code is as follows:

# Src/Acme/BlogBundle/Resources/config/validation. yml
Acme \ BlogBundle \ Entity \ Author:
Properties:
Name:
-NotBlank :~


Class declaration format:

The Code is as follows:

// Src/Acme/BlogBundle/Entity/Author. php
Use 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"?>
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://symfony.com/schema/dic/constraint-mapping">






PHP code format:

The Code is 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 attributes and the getter method can also be verified.

Use the validator service:

Next, use the validate method of the validator service to verify the Author object. Validator's work is very simple: Read the constraint rules of a class to verify whether the data of an object meets the constraints of these rules. If verification fails, an error array is returned. Now we can 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 attribute is empty, you will see the following error message:

Acme \ BlogBundle \ Author. name:
This value shoshould not be blank

If you insert a value for the $ name attribute, you will get a happy success message.

Most of the time, you do not need to communicate directly with the validator service or simply do not need to worry about printing errors.

In most cases, you will use verification when processing the submitted form data.

You can also pass an error message set 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 has the following errros


    {% For error in errors %}
  • {Error. message }}

  • {% Endfor %}

Checksum form

The validator service can be used to verify any object at any time. In fact, you will often use validator when processing forms. The Form class library of Symfony indirectly uses the validator service to verify the underlying object after the data is submitted and bound. The object violation information will be converted to the FieldError object, which can be easily 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;
//...

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.