The*_*ebs 3 php doctrine-orm symfony-validator
所以我不确定这里的问题是什么,或者这个类是如何加载的。但我的模型(或者他们实际所说的实体)看起来像这样:
<?php
namespace ImageUploader\Models;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="users")
* @UniqueEntity(fields="userName")
* @UniqueEntity(fields="email")
*/
class User {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(type="string", length=32, nullable=false)
* @Assert\NotBlank()
*/
protected $firstName;
/**
* @ORM\Column(type="string", length=32, nullable=false)
* @Assert\NotBlank()
*/
protected $lastName;
/**
* @ORM\Column(type="string", length=100, unique=true, nullable=false)
* @Assert\NotBlank(
* message = "Username cannot be blank"
* )
*/
protected $userName;
/**
* @ORM\Column(type="string", length=100, unique=true, nullable=false)
* @Assert\NotBlank()
* @Assert\Email(
* message = "The email you entered is invalid.",
* checkMX = true
* )
*/
protected $email;
/**
* @ORM\Column(type="string", length=500, nullable=false)
* @Assert\NotBlank(
* message = "The password field cannot be empty."
* )
*/
protected $password;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $created_at;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $updated_at;
}
Run Code Online (Sandbox Code Playgroud)
在我的文件中,我有一个名为的操作createAction,当用户尝试注册时会调用该操作。它看起来像这样:
public static function createAction($params){
$postParams = $params->request()->post();
if ($postParams['password'] !== $postParams['repassword']) {
$flash = new Flash();
$flash->createFlash('error', 'Your passwords do not match.');
$params->redirect('/signup/error');
}
$user = new User();
$user->setFirstName($postParams['firstname'])
->setLastName($postParams['lastname'])
->setUserName($postParams['username'])
->setEmail($postParams['email'])
->setPassword($postParams['password'])
->setCreatedAtTimeStamp();
$validator = Validator::createValidatorBuilder();
$validator->enableAnnotationMapping();
$errors = $validator->getValidator()->validate($user);
var_dump($errors);
}
Run Code Online (Sandbox Code Playgroud)
当调用此操作时,我收到以下错误:
Fatal error: Class 'doctrine.orm.validator.unique' not found in /var/www/html/image_upload_app/vendor/symfony/validator/ConstraintValidatorFactory.php on line 47
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个问题。我的作曲家文件是这样的:
{
"require": {
"doctrine/orm": "2.4.*",
"doctrine/migrations": "1.0.*@dev",
"symfony/validator": "2.8.*@dev",
"symfony/doctrine-bridge": "2.8.*@dev",
"slim/slim": "~2.6",
"freya/freya-exception": "0.0.7",
"freya/freya-loader": "0.2.2",
"freya/freya-templates": "0.1.2",
"freya/freya-factory": "0.0.8",
"freya/freya-flash": "0.0.1"
},
"autoload": {
"psr-4": {"": ""}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我不确定我是否丢失了包裹或者我是否做错了什么......
我的bootstrap.php文件中有以下内容:
require_once 'vendor/autoload.php';
$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
/**
* Set up Doctrine.
*/
class DoctrineSetup {
/**
* @var array $paths - where the entities live.
*/
protected $paths = array(APP_MODELS);
/**
* @var bool $isDevMode - Are we considered "in development."
*/
protected $isDevMode = false;
/**
* @var array $dbParams - The database paramters.
*/
protected $dbParams = null;
/**
* Constructor to set some core values.
*/
public function __construct(){
if (!file_exists('db_config.ini')) {
throw new \Exception(
'Missing db_config.ini. You can create this from the db_config_sample.ini'
);
}
$this->dbParams = array(
'driver' => 'pdo_mysql',
'user' => parse_ini_file('db_config.ini')['DB_USER'],
'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
);
}
/**
* Get the entity manager for use through out the app.
*
* @return EntityManager
*/
public function getEntityManager() {
$config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
return EntityManager::create($this->dbParams, $config);
}
}
/**
* Function that can be called through out the app.
*
* @return EntityManager
*/
function getEntityManager() {
$ds = new DoctrineSetup();
return $ds->getEntityManager();
}
/**
* Function that returns the conection to the database.
*/
function getConnection() {
$ds = new DoctrineSetup();
return $ds->getEntityManager()->getConnection();
}
Run Code Online (Sandbox Code Playgroud)
我是否需要添加其他内容才能消除此错误?
所以我继续设置,AppKernel因为我以前没有,并且因为我不相信我需要config.yml(至少现在还不需要)。一切似乎都正常 - 内核方面,但错误仍然存在。
namespace ImageUploader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel {
public function registerBundles() {
$bundles = array(
new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle()
);
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader) {}
}
Run Code Online (Sandbox Code Playgroud)
然后我在引导文件中启动内核,添加:
use \ImageUploader\AppKernel;
$kernel = new AppKernel();
$kernel->boot();
Run Code Online (Sandbox Code Playgroud)
从我读到的内容来看,一切都是正确的 - 减去丢失的配置文件,这不应该是一个问题。但我仍然收到有问题的错误
小智 6
我是如何解决这个问题的:
首先,创建一个自定义 ConstraintValidatorFactory ,它允许我添加验证器
<?php
namespace My\App\Validator;
use Symfony\Component\Validator\ConstraintValidatorFactory as SymfonyConstraintValidatorFactory;
use Symfony\Component\Validator\ConstraintValidatorInterface;
/**
* Class ConstraintValidatorFactory
*
* @package My\App\Validator
*/
class ConstraintValidatorFactory extends SymfonyConstraintValidatorFactory
{
/**
* @param string $className
* @param ConstraintValidatorInterface $validator
*
* @return void
*/
public function addValidator($className, $validator): void
{
$this->validators[$className] = $validator;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以这样做:
<?php
use My\App\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Validation;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;
$factory = new ConstraintValidatorFactory();
$factory->addValidator('doctrine.orm.validator.unique', new UniqueEntityValidator($registry));
$builder = Validation::createValidatorBuilder();
$builder->setConstraintValidatorFactory($factory);
$builder->enableAnnotationMapping();
$validator = $builder->getValidator();
$violations = $validator->validate($entity);
Run Code Online (Sandbox Code Playgroud)
这对我有用,使用 symfony 组件和 zend 服务管理器。
请记住,Symfony 的 UniqueEntityValidator 依赖于 \Doctrine\Common\Persistence\ManagerRegistry.
我在项目中使用单个 EntityManager,并且必须将其包装在 ManagerRegistry 类中才能完成这项工作。