0

I'm trying to get the ago datetime using KnpTimeBundle .
As the documentaion says , i need to use the helper class to acess to diff() function :
Take a look to my controller.php :

use Knp\Bundle\TimeBundle\Templating\Helper as Helper;

/**
 * @Route("/test",name="test")
 * @Method({"GET","POST"})
 */
public function testAction(Request $request){
$date = new \DateTime("now");
$h=new Helper();// here i got a 404 error
$ago=$h->diff($date);
return $this->render('test.html.twig', array());
}

But calling the Helper class by this way didnt work for me , can any one give me the right way to do the trick .

famas23
  • 2,072
  • 4
  • 17
  • 53

1 Answers1

0

I just Create my own service no need for the bundle :

<?php
namespace AppBundle\Services;

class Helpers {
public function pluralize( $count, $text ) 
{ 
    return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}

function ago( $datetime )
{
    $interval = date_create('now')->diff( $datetime );
    $suffix = ( $interval->invert ? ' ago' : '' );
    if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->y, 'year' ) . $suffix;
    if ( $v = $interval->m >= 1 ) return $this->pluralize( $interval->m, 'month' ) . $suffix;
    if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day' ) . $suffix;
    if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour' ) . $suffix;
    if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute' ) . $suffix;
    return $this->pluralize( $interval->s, 'second' ) . $suffix;
}  

in my services.yml: services:

app.helpers:
    class: AppBundle\Services\Helpers
    arguments: [ "@doctrine.orm.entity_manager" , "@service_container" ]

then i just called :

$helpers = $this->get("app.helpers");
$helpers->ago($date);
famas23
  • 2,072
  • 4
  • 17
  • 53