Symfony2 - Twig Extension错误无法访问空属性

时间:2014-07-04 06:58:17

标签: php symfony twig

使用Twig扩展的新手,可以对此使用一些帮助 - 无法弄清楚出了什么问题。

除了我的扩展类中的函数调用之外,所有内容似乎都正确加载。

我收到以下错误:

FatalErrorException:Error:Cannot access property in /../PostExtension.php line 32

第32行:

public function getPostCount($year, $month)

一直在寻找解决方案并阅读几个小时的文档而无法找到解决方案。 对此有何帮助?

PostExtension.php

class PostExtension extends \Twig_Extension
{
private $em;

public function __construct(EntityManager $em)
{
    $this->em = $em;
}

public function getFilters()
{
    return array(
    );
}

public function getFunctions()
{
    return array(
        'getPostCount' => new \Twig_Function_Method($this, 'getPostCount')
    );
}

public function getPostCount($year, $month)
{
    $post = $this->$em->getRepository('AcmeDemoBundle:Post')
        ->getPostCountsByMonth($year, $month);

    return $post;
}

public function getName()
{
    return 'post_extension';
}
}

枝条

{{ getPostCount('2014', 'July') }}

services.yml

services:
    acme.twig.extension:
        class: Acmer\DemoBundle\Twig\PostExtension
        tags:
            - { name: twig.extension }
        arguments:
            em: "@doctrine.orm.entity_manager"

存储库 - getPostCountsByMonth

public function getPostCountsByMonth($year, $month)
{
    // Query for blog posts in each month
    $date = new \DateTime("{$year}-{$month}-01");
    $toDate = clone $date;
    $toDate->modify("next month midnight -1 second");

    $query = $this->createQueryBuilder('post')
        ->where('post.created BETWEEN :start AND :end')
        ->addOrderBy('post.created', 'DESC')
        ->setParameter('start', $date)
        ->setParameter('end', $toDate);

    $query->select('COUNT(post.created)');

    $month = $query
        ->getQuery()
        ->getSingleScalarResult();

    return $month;
}

1 个答案:

答案 0 :(得分:3)

您的getPostCount()方法中存在拼写错误。

在这一行$this->$em上你应该删除第二个$符号,因为你想访问em属性,所以你应该这样使用它:

$post = $this->em->getRepository('AcmeDemoBundle:Post')
    ->getPostCountsByMonth($year, $month);