如何在您创建的捆绑包中实现Symfony验证器?
我有一个Extension类、一个CompilerPass和一个"services.xml"文件。
验证器应该被注入中间件中,我在扩展中尝试使用:$container->registerForAutoConfiguration(ValidatorInterface::class)->addTag(...);
,但如果我尝试在CompilerPass中查找标记并转储密钥,那么它就会声称我请求了一个未定义的服务。
您需要验证一些东西,例如信使中间件:
<?php declare(strict_types=1);
namespace UserMyBundleMiddleware;
use SymfonyComponentMessengerMiddlewareMiddlewareInterface;
use SymfonyComponentMessengerMiddlewareStackInterface;
use SymfonyComponentMessengerEnvelope;
use SymfonyComponentValidatorValidatorValidatorInterface;
final class ValidationMiddleware implements MiddlewareInterface
{
private ValidatorInterface $validator;
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$errors = $this->validator->validate($envelope->getMessage());
if (!empty($errors)) {
// exception
}
return $stack->next()->handle($envelope, $stack);
}
}
并使用validator
作为服务注入配置的id:
<!-- file: src/Resources/config/services.xml -->
<service id="my.middleware.validator" class="UserMyBundleMiddlewareValidatorMiddleware">
<tag name="messenger.middleware" />
<argument type="service" id="validator" />
</service>
然后使用PrependExtensionInterface
:在Extension类的普通应用程序中配置框架
<?php declare(strict_types=1);
namespace UserMyBundleDependencyInjection;
use SymfonyComponentDependencyInjectionContainerBuilder;
use SymfonyComponentDependencyInjectionExtensionPrependExtensionInterface;
use SymfonyComponentHttpKernelDependencyInjectionExtension;
class UserMyExtension extends Extension implements PrependExtensionInterface
{
public function load(array $configs, ContainerBuilder $container)
{
// configure dependencies
}
public function prepend(ContainerBuilder $container)
{
$container->prependExtensionConfig('framework', [
'validation' => [
'enabled' => true,
'enable_annotations' => false,
'mapping' => [
'paths' => [
__DIR__ . "/../Resources/config/validation/validator.xml",
],
],
],
]);
}
}
如果我们采取一种更简单的方法呢。您可以通过在自述文件中添加一个简单的安装说明来告诉捆绑包的用户安装验证规则,该说明告诉用户编辑config/packages/validator.yaml
auto_mapping:
YourVendorYourBundleEntity: []
mapping:
paths:
- '%kernel.project_dir%/lib/src/YourBundle/Resources/config/validator.yaml'
上面显示的示例的目录位于项目目录中。为了方便,可以对其进行编辑。在您的validator.yaml
文件中,您可以将验证规则
YourVendorYourBundleEntityInstitution:
properties:
email:
- Email: { message: Please Enter a Valid Email Address }
constraints:
- YourVendorYourBundleValidatorsInstitutionClosingTime: ~