I need to use Traits in symfony2. Different repositories extending different parents still use some common methods. I have created a trait that will contain those common methods. Unfortunately, when I call the action, Symfony2 throws an error saying :
Parse Error: syntax error, unexpected 'Trait' (T_TRAIT), expecting identifier (T_STRING)
in src/AppBundle/Entity/Repository/CategoryRepository.php line 14
Here is one of the repositories
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;
}
}
And here is the Trait :
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;
}
}
I'm using PHP 5.6 and Traits work (I've run a little simple test outside the project). I don't understand what's wrong.