Symfony2 -树枝扩展错误无法访问空属性


Symfony2 - Twig Extension error cannot access empty property

新手使用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"

Repository - 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;
}

你的getPostCount()方法中有一个打字错误。

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

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