2015-07-21 76 views
0

我需要在symfony2中使用traits。扩展不同父母的不同储存库仍然使用一些常用方法。我创建了一个包含这些常用方法的特征。不幸的是,当我打电话的动作,Symfony2的抛出一个错误的说法:Symfony2中的特征错误

Parse Error: syntax error, unexpected 'Trait' (T_TRAIT), expecting identifier (T_STRING) 
in src/AppBundle/Entity/Repository/CategoryRepository.php line 14 

这里是仓库

namespace AppBundle\Entity\Repository; 

use Gedmo\Tree\Entity\Repository\NestedTreeRepository; 
use AppBundle\Trait\HasDomainRepositoryTrait; 
/** 
* CategoryRepository 
* 
* This class was generated by the Doctrine ORM. Add your own custom 
* repository methods below. 
*/ 
class CategoryRepository extends NestedTreeRepository 
{ 
    use HasDomainRepositoryTrait; 

    public function search($domain, $onlyActive, $searchString = null) 
    { 
     $builder = $this->createBaseQuery($domain, $onlyActive); 

     if ($searchString) { 
      $builder 
        ->andWhere('e.name LIKE :searchString') 
        ->setParameter('searchString', '%'.strtolower($searchString).'%') 
        ; 
     } 

     return $builder; 
    } 
} 

这里的一个特质:

namespace AppBundle\Trait; 

trait HasDomainRepositoryTrait 
{ 
    public function createBaseQuery($domain, $onlyActive = false) 
    { 
     $builder = $this->createQueryBuilder('e'); 

     if ($domain) { 
      $builder 
        ->andWhere('e.domain = :domain') 
        ->setParameter('domain', $domain) 
        ; 
     } 

     if ($onlyActive) { 
      $qb->andWhere(sprintf('e.enabled = %s', $onlyActive)); 
     } 

     return $builder; 
    } 
} 

我使用PHP 5.6和Traits工作(我在项目之外运行了一些简单的测试)。 我不明白什么是错的。

+1

您可能无法使命名空间为“特质”。尝试将名称空间更改为其他名称。 – Jessica

+1

就是这样,谢谢。让它成为答案,我会接受它。 – Hakim

回答

6

您可能无法使您的名称空间为“特质”。尝试将名称空间更改为其他名称。

+0

耻辱,这是这种情况。它的工作,但似乎很愚蠢,我不知道为什么这个限制存在。 – Ryall

+1

@Ryall我认为是一样的。我使用了命名空间“Mixin”,但是我的特征被命名为“'ChosenNameTrait”,您选择了哪一个? – Gus

+0

@Gus好主意 - 这是一个很好的选择 – Ryall