gpt4 book ai didi

php - 如何安全地使用 UniqueEntity(在同时有多个用户的网站上)

转载 作者:可可西里 更新时间:2023-11-01 12:38:00 25 4
gpt4 key购买 nike

聪明的人可以分享他们使用的设计模式来避免 Doctrine\Symfony 中这个基本和常见的并发问题吗?

场景:每个用户必须有一个唯一的用户名。

失败的解决方案:

失败原因:在验证和保留用户之间,用户名可能被其他用户使用。如果是这样,Doctrine 在尝试保留最新的用户时抛出 UniqueConstraintViolationException。

最佳答案

这是我的以下答案的作用:

  • 如果发生约束违规,它会优雅地向用户显示错误,就像验证器处理它一样,

  • 它可以防止未“ protected ” 的数据库更新破坏您的 Controller 逻辑(例如使用 UPDATE 语句或带有“未 protected ” 的表单提交) Controller ),

  • 这是一个独立于数据库的解决方案。

代码如下,附注释说明:

<?php

// ...

use Doctrine\DBAL\Exception\ConstraintViolationException;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper;

// ...

public function indexAction(Request $request)
{
$task = new Task();

$form = $this->createFormBuilder($task)
->add('name', TextType::class)
->add('save', SubmitType::class, array('label' => 'Create Task'))
->getForm();

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
$task = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($task);

try {
$em->flush();

// Everything went well, do whatever you're supposed to.
return $this->redirectToRoute('task_success');
} catch (ConstraintViolationException $e) {
// Reopen the entity manager so the validator can do jobs
// that needs to be performed with the database (in example:
// unique constraint checks)
$em = $em->create($em->getConnection(), $em->getConfiguration());

// Revalidate the form to see if the validator knows what
// has thrown this constraint violation exception.
$violations = $this->get('validator')->validate($form);

if (empty($violations)) {
// The validator didn't see anything wrong...
// It can happens if you have a constraint on your table,
// but didn't add a similar validation constraint.

// Add an error at the root of the form.
$form->add(new FormError('Unexpected error, please retry.'));
} else {
// Add errors to the form with the ViolationMapper.
// The ViolationMapper will links error with its
// corresponding field on the form.
// So errors are not displayed at the root of the form,
// just like if the form was validated natively.
$violationMapper = new ViolationMapper();

foreach ($violations as $violation) {
$violationMapper->mapViolation($violation, $form);
}
}
}
}

return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
}

关于php - 如何安全地使用 UniqueEntity(在同时有多个用户的网站上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com