[英]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"
储存库-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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.