如何在不重复查询的情况下使对象在整个symfony2应用程序中可用


How to make object available throughout symfony2 app without repeating the query?

如何在Symfony中跨视图共享对象

我在实体中实现了类Serializable,这样我就可以将对象存储在会话中。然而,由于我的实体包含抽象方法,我需要在类中实现可序列化方法,我相信这将是我的最后手段。

在那之前,我想找到一个替代的解决方案,而不是将对象存储在数据库中的临时表中(这与什么都不做完全一样,因为我需要调用每个显示视图的控制器中的数据库)

这是我的场景:

我有两个文件:layout.html.twigsidebar.html.twig

我的DefaultController中有一个名为buildSidebar()的方法,如下所示

public function buildSidebar($userId = 0) {
    $projects = $this->getDoctrine()->getRepository('SuperBundle:Projects')->findBy(array('userId' => $userId), array('cratedDate' => DESC), 10);
    return $this->render(
            'SuperBundle:sidebar.html.twig',
            array('projects' => $projects)
    );
}

然后在我的layout.html.twig文件中,第77行有以下代码块:

{% render controller("SuperBundle:Default:buildSidebar", {'userId': 37})  %}

当我测试它时,symfony抛出一个异常,说:

function controller doesn't exist in SuperBundle::layout.html.twig in line 77

我试着用这种方式嵌入控制器:

{{ render(controller("SuperBundle:Default:buildSidebar", {'userId': 37}) }}

此方法抛出异常unexpected name of value controller:

{{ render controller("SuperBundle:Default:buildSidebar", {'userId': 37}) }}

我也用这种方式尝试过,得到了相同的结果function controller does not exist:

{%render(控制器("SuperBundle:默认:buildSidebar",{'userId':37})%}

我错过了什么?我仔细阅读了Symfony的文件,其中也没有任何帮助。

是的,您可以通过分支扩展从访问服务。http://symfony.com/doc/current/cookbook/templating/twig_extension.html

<?php
namespace You'UserBundle'Twig;
use Symfony'Component'Security'Core'SecurityContext;

class YourExtension extends 'Twig_Extension
{
    protected $doctrine;
    function __construct($doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function getUsers()
    {
        $em = $this->doctrine->getManager();
        $result = $em
            ->getRepository('yourEntity')->findAll();
        return $result;
    }
    public function getFunctions()
    {
        return array(
            new 'Twig_SimpleFunction('get_users', array($this, 'getUsers'))
        );
    }
    public function getName()
    {
        return 'your_extension';
    }
}

或者你可以在你的树枝视图中包括一个控制器,比如:

        {{ render(controller('YourUserBundle:YourController:youraction')) }}

来源:http://symfony.com/blog/new-in-symfony-2-2-the-new-fragment-sub-framework