也许你可以像这样创建一个 ConstraintViolationsEvent :
namespace AppBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Validator\ConstraintViolationListInterface;
/**
* The order.placed event is dispatched each time an order is created
* in the system.
*/
class ConstraintViolationsEvent extends Event
{
const VIOLATIONS_DETECTED = 'constraint_violations.detected';
protected $constraintViolationList;
public function __construct(ConstraintViolationListInterface $constraintViolationList)
{
$this->constraintViolationList = $constraintViolationList;
}
public function getConstraintViolationList()
{
return $this->constraintViolationList;
}
}
然后,您可以为此事件创建一个侦听器,并在此侦听器中,根据发现的所有违规行为创建您的异常。每次您会发现违规行为时,您只需在控制器中发送事件,如下所示:
class MyController extends Controller
{
public function myFormAction(Request $request)
{
/** handle the request, get the form data, validate the form...etc. **/
$event = new ConstraintViolationsEvent($constraintViolationList);
$dispatcher->dispatch(ConstraintViolationsEvent::VIOLATIONS_DETECTED, $event);
}
}
实际上,您可以在服务中管理 Exception 的创建并在侦听器中调用该服务。它是由你决定。