2012-10-18 3 views
1

보안 번들을 사용하여 Symfony에서 설정 한 인증 역할이 다릅니다.Symfony - 인증 역할에 따른 가격 표시

* Wholesale 
* Detailing 
* Public 

사용자가 로그인 한 인증에 따라 제품에 대해 다른 가격을 표시하려고합니다. 내 제품 엔티티에서

나는

$protected wholesalePrice; 
$protected detailingPrice; 
$protected publicPrice; 

내가 특정 인증 역할에 대한 가격을 얻기 위해 하나 개의보기를 사용하거나 내가 3 가지 뷰를 생성해야 있나요?

답변

3

템플릿을 통해 액세스하려면 서비스와 나뭇 가지 확장을 만드는 것이 좋습니다.

만 같은 것을해야 할 것입니다 그런 식으로 :

{{ 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.'); 
    } 
} 
2

이 같은 is_granted()를 사용하여 하나 개의보기로 작업을 수행 할 수 있습니다

{% if is_granted('ROLE_A') %} 
    {{ product.wholesalePrice }} 
{% elseif is_granted('ROLE B') %} 
    {{ product.detailingPrice }} 
{% elseif is_granted('ROLE C') %} 
    {{ product.publicPrice }} 
{% endif %} 

는 도움이되기를 바랍니다.

+2

@ 알렉스 조이스 대답이 나보다 낫다. 내 솔루션은 더 간단하지만이 역할 검사가 여러 템플릿에 있어야하는 경우 Service + Twig Extension 솔루션을 선택해야합니다. –

관련 문제