我正在向Symfony2项目添加自定义验证查询.
The docs缺少一个完整的例子,我不知道如何将数据库连接实际注入到验证器类中.我在我的配置中创建了服务,在我的Constraint类中添加了validatedBy别名方法,并在我的验证器类中设置了这个:
use Doctrine\DBAL\Connection; class ZipDatabaseValidator extends ConstraintValidator { /** * * @var Connection */ private $connection; public function __construct(Connection $dbalConnection) { $this->connection = $dbalConnection; } public function validate($zipcode,Constraint $constraint) { $sql = 'SELECT * FROM zip_table WHERE zip_code = ?'; $stmt = $this->connection->prepare($sql); ...
这是我的服务配置:
validator.node.zip_in_database: class: Acme\Bundle\Validator\Constraints\ZipDatabaseValidator arguments: [@database_connection] tags: - { name: validator.constraint_validator,alias: zip_in_database }
在这种情况下,我会收到错误:
Catchable Fatal Error: Argument 1 passed to
Acme\Bundle\Validator\Constraints\ZipDatabaseValidator::__construct()
must be an instance of Doctrine\DBAL\Connection,none given,
我如何将其设置为服务或以其他方式注入数据库连接?
解决方法
validator.node.zip_in_database: class: Acme\Bundle\Validator\Constraint\ZipDatabaseValidator arguments: [@database_connection] tags: - { name: validator.constraint_validator,alias: zip_in_database }
你必须通过教条作为你的Service的参数.
编辑
确保别名与validatedBy方法返回相同!
在你的情况下:
//Acme\Bundle\Validator\Constraint\ZipDatabase class public function validatedBy() { return 'zip_in_database'; }