dqf42223 2014-07-04 06:58
浏览 40
已采纳

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

New to using Twig extensions, can use some help on this—can't figure out what is wrong.

Everything seems to be loading up correctly except with the function call in my extension class.

Am getting the following error:

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

Line 32:

public function getPostCount($year, $month)

Have been searching for solutions and reading docs for hours and haven't been able to find the solution. Any help on this?

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

Twig

{{ 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;
}
  • 写回答

1条回答 默认 最新

  • duangewu5234 2014-07-04 08:04
    关注

    You have a typo inside your getPostCount() method.

    On this line $this->$em you should remove the second $ sign because you want to access em property so you should use it like this:

    $post = $this->em->getRepository('AcmeDemoBundle:Post')
        ->getPostCountsByMonth($year, $month);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器