【发布时间】:2017-06-23 19:27:46
【问题描述】:
我正在使用 symfony 组件在 Silex 中进行一些编程,我想我发现了 symfony/serializer 和 symfony/validator 组件的错误。
首先让我解释一下我训练要实现的目标,然后我们来看代码。
我的目标是用序列化指令和验证指令等信息来注释一个类。由于读取这些注释可能会消耗很少的 CPU,因此我喜欢将它们缓存在内存中。为此,我在 Doctrine/Common/Cache 包中使用了 memcache 包装器。
我面临的问题是symfony/serializer 和symfony/validator 都使用类名作为键将元数据写入缓存。当他们稍后尝试检索元数据时,他们会抛出异常,因为缓存中有无效的元数据,Symfony\Component\Validator\Mapping\ClassMetadata 或 Symfony\Component\Serializer\Mapping\ClassMetadataInterface 的实例。
以下是一个可复制的示例(对不起,如果它很大,我试图尽可能小):
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
class Foo
{
/**
* @var int
* @Assert\NotBlank(message="This field cannot be empty")
*/
private $someProperty;
/**
* @return int
* @Groups({"some_group"})
*/
public function getSomeProperty() {
return $this->someProperty;
}
}
use Doctrine\Common\Annotations\AnnotationReader;
use \Memcache as MemcachePHP;
use Doctrine\Common\Cache\MemcacheCache as MemcacheWrapper;
$loader = require_once __DIR__ . '/../vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
$memcache = new MemcachePHP();
if (! $memcache->connect('localhost', '11211')) {
throw new \Exception('Unable to connect to memcache server');
}
$cacheDriver = new MemcacheWrapper();
$cacheDriver->setMemcache($memcache);
$app = new \Silex\Application();
$app->register(new Silex\Provider\SerializerServiceProvider());
$app['serializer.normalizers'] = function () use ($app, $cacheDriver) {
$classMetadataFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader(new AnnotationReader()), $cacheDriver);
return [new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer($classMetadataFactory) ];
};
$app->register(new Silex\Provider\ValidatorServiceProvider(), [
'validator.mapping.class_metadata_factory' =>
new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(
new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader(new AnnotationReader()),
new \Symfony\Component\Validator\Mapping\Cache\DoctrineCache($cacheDriver)
)
]);
$app->get('/', function(\Silex\Application $app) {
$foo = new Foo();
$app['validator']->validate($foo);
$json = $app['serializer']->serialize($foo, 'json');
return new \Symfony\Component\HttpFoundation\JsonResponse($json, \Symfony\Component\HttpFoundation\Response::HTTP_OK, [], true);
});
$app->error(function (\Exception $e, \Symfony\Component\HttpFoundation\Request $request, $code) {
return new \Symfony\Component\HttpFoundation\Response('We are sorry, but something went terribly wrong.' . $e->getMessage());
});
$app->run();
运行此示例后,您会遇到致命错误。 谁能确认我在这里没有犯严重的错误?
目前我的解决方法是重写DoctrineCache 类,使用缓存键的命名空间。它可以工作,但我认为它很丑。
【问题讨论】:
标签: php validation symfony silex serialization