템플릿을 통해 액세스하려면 서비스와 나뭇 가지 확장을 만드는 것이 좋습니다.
만 같은 것을해야 할 것입니다 그런 식으로 :
{{ product | priceByRole }}
보안 로직을 처리하는이 "역할에 의해 가격"당신에 액세스 할 서비스.
서비스 : 나뭇 가지 확장을 작성 http://symfony.com/doc/current/book/service_container.html : http://symfony.com/doc/2.0/cookbook/templating/twig_extension.html
예 나뭇 가지 확장 :
<?php
namespace Acme\DemoBundle\Twig;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PriceByRoleExtension extends \Twig_Extension implements ContainerAwareInterface
{
protected $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function getFilters()
{
return array(
'priceByRole' => new \Twig_Filter_Method($this, 'priceByRoleFilter'),
);
}
public function priceByRoleFilter(Item $entity)
{
$service = $this->container->get('my.price.service');
return $service->getPriceFromEntity($entity);
}
public function getName()
{
return 'acme_extension';
}
}
예 서비스 :
<?php
namespace Acme\DemoBundle\Service;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Acme\DemoBundle\Entity\Product;
class PriceService
{
protected $context;
public function setSecurityContext(SecurityContextInterface $context = null)
{
$this->context = $context;
}
public function getPriceFromEntity(Product $product)
{
if ($this->context->isGranted('ROLE_A'))
return $product->getWholesalePrice();
if ($this->context->isGranted('ROLE_B'))
return $product->getDetailingPrice();
if ($this->context->isGranted('ROLE_C'))
return $product->getPublicPrice();
throw new \Exception('No valid role for any price.');
}
}
@ 알렉스 조이스 대답이 나보다 낫다. 내 솔루션은 더 간단하지만이 역할 검사가 여러 템플릿에 있어야하는 경우 Service + Twig Extension 솔루션을 선택해야합니다. –