Skip to content

Instantly share code, notes, and snippets.

@n3b
Created July 24, 2011 00:56
Show Gist options
  • Save n3b/1102062 to your computer and use it in GitHub Desktop.
Save n3b/1102062 to your computer and use it in GitHub Desktop.
Symfony2. Getting service in template.
<?php
namespace MyBundle\Service;
class Catalog
{
protected $em;
public function __construct($em)
{
$this->em = $em;
}
public function getItems()
{
if(!isset($this->items))
$this->items = $this->em->getRepository('MyBundle:Item')->findAll();
return $this->items;
}
}
<?php
namespace MyBundle\Templating\Catalog;
use MyBundle\Service\Catalog as CatalogService;
use Symfony\Component\Templating\Helper\Helper;
class Catalog extends Helper
{
protected $catalog;
public function __construct(CatalogService $cs)
{
$this->catalog = $cs;
}
public function getItems()
{
return $this->catalog->getItems();
}
public function getName()
{
return 'catalog';
}
}
services:
catalog:
class: MyBundle\Service\Catalog
arguments:
services:
em: '@doctrine.orm.entity_manager'
helper.catalog:
class: MyBundle\Templating\Catalog
arguments:
catalog_service: '@catalog'
tags:
- { name: templating.helper, alias: catalog }
<ul>
<?php foreach($view['catalog']->getItems() as $item): ?>
<li>
<?php echo $item->getTitle() ?>
</li>
<?php endforeach ?>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment