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