


Symfony data verification method example analysis, symfony example analysis_PHP tutorial
Symfony data verification method example analysis, symfony example analysis
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.
namespace AcmeBlogBundleEntity;
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:
AcmeBlogBundleEntityAuthor:
Properties:
name:
- NotBlank: ~
Class declaration format:
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertNotBlank()
*/
Public $name;
}
XML format:
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
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:
use AcmeBlogBundleEntityAuthor;
//...
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:
Return $this->render('AcmeBlogBundle:Author:validate.html.twig',array(
'errors' => $errors,
));
}else{
//...
}
In the template, you can output the error list as accurately as you need:
Twig format:
The author has the following errros
- {{ error.message }}
{% for error in errors %}
{% endfor %}
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:
use AcmeBlogBundleFormAuthorType;
use AcmeComponentHttpFoundationRequest;
//...
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:
framework:
Validation: {enable_annotations: true }
XML format:
PHP code format:
$contianer->loadFromExtension('framework',array('validation'=> array(
'enable_annotations'=>true,
)));
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:
AcmeBlogBundleEntityAuthor:
Properties:
gener:
- Choice: { choices: [male, female], message: Choos a valid gender. }
Class declaration format:
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertChoice(
* choices = {"male","female"},
* message = "Choose a valid gender."
* )
*/
Public $gender;
}
XML format:
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
in
& Lt; option name = "Message" & gt; Choose a valid gender. & Lt;/option & gt;
PHP code format:
Copy code
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsNotBlank;
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:
AcmeBlogBundleEntityAuthor:
Properties:
gender:
- Choice: [male, female]
Class declaration format:
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertChoice({"male", "female"})
*/
protected $gender;
}
XML format:
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
PHP format:
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsChoice;
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:
AcmeBlogBundleEntityAuthor:
Properties:
firstName:
- NotBlank: ~
- MinLength: 3
Class declaration format:
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertNotBlank()
* @AssertMinLength(3)
*/
Private $firstName;
}
XML format:
PHP code format:
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsNotBlank;
use SymfonyComponentValidatorConstraintsMinLength;
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:
AcmeBlogBundleEntityAuthor:
Getters:
passwordLegal:
- "True": { message: "The password cannot match your first name" }
Class declaration format:
use SymfonyComponentValidatorConstraints as Assert;
class Author
{
/**
* @AssertTrue(message = "The password cannot match your first name")
*/
Public function isPasswordLegal()
{
// return true or false
}
}
XML format:
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraintsTrue;
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:
{
Return ($this->firstName != $this->password);
}
The eagle-eyed may notice that the getter prefix ("get" or "is") is ignored when mapping. This allows you to move a constraint to a property with the same name, or vice versa, without changing the validation rules.
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:
AcmeBlogBundleEntityUser:
Properties:
email:
- Email: { groups: [registration] }
Password:
- NotBlank: { groups: [registration] }
- MinLength: { limit: 7, groups: [registration] }
city:
- MinLength: 2
Class declaration format:
namespace AcmeBlogBundleEntity;
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代码格式:
namespace AcmeBlogBundleEntity;
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:
use SymfonyComponentValidatorConstraintsEmail;
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.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),