通过在数据库中存储几个模板(如this answer中所示),数据库查询的数量将大大增加。例如,分析器显示,页面上的20个查询中有12个与搜索模板有关,尽管数据库中没有任何查询。我的印象是,只有在文件结构中没有模板时,才会进行搜索。是否只有当所需的模板不在文件结构中时,才有方法查询数据库?
更新1:
实验表明,注释掉vol.volbundle.twig_database_loader服务的vol.volbundle.twig_database_loader部分可以消除不必要的查询,但仍然可以在数据库中找到模板。如果没有tags块,则会发生以下错误
InvalidArgumentException:模板名"new_opp“无效(格式为"bundle:section:template.format.engine”)
当模板被编辑时,持久化并尝试用以下代码从缓存中删除其前身。有了tags块,缓存的模板就会被删除!似乎是这样的,因为tags块允许在缓存删除期间找到数据库加载器。
$fileCache = $this->container->get('twig')->getCacheFilename($name);
if (is_file($fileCache)) {
@unlink($fileCache);
} 因此,当不存在块时,控制器使用数据库加载程序是很奇怪的。
services.yml
vol.volbundle.twig_database_loader:
class: Vol\VolBundle\Tools\TwigDatabaseLoader
arguments: [@doctrine.orm.entity_manager]
tags:
- { name: twig.loader }TwigDatabaseLoader
namespace Vol\VolBundle\Tools;
use \Twig_Error_Loader;
/**
* Description of DatabaseTwigLoader
*
*/
class TwigDatabaseLoader implements \Twig_LoaderInterface
{
private $entityManager;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function getSource($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return $source;
}
public function isFresh($name, $time)
{
if (false === $lastModified = $this->getValue('last_modified', $name)) {
return false;
}
return $lastModified <= $time;
}
public function getCacheKey($name)
{
// check if exists
return 'db:' . $name;
}
protected function getValue($column, $name)
{
$conn = $this->entityManager->getConnection();
$sth = $conn->prepare('SELECT '.$column.' FROM template WHERE name = :name');
$sth->execute(array(':name' => (string) $name));
return $sth->fetchColumn();
}
}编译器
namespace Vol\VolBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Description of TwigDatabaseLoaderPass
*
*/
class TwigDatabaseLoaderPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('twig');
$definition->addMethodCall('setLoader', array(new Reference('vol.volbundle.twig_database_loader')));
}
}发布于 2014-07-04 22:15:18
事实证明,大量的查询只发生在dev模式下!这是通过在MySQL中启用查询日志来确定的。对模板进行编辑,然后呈现它,然后查看日志,结果显示只有存储的模板调用了模板查询。查询日志中没有出现任何其他模板。案子结案了!
https://stackoverflow.com/questions/24556354
复制相似问题