1

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.

2
  • 2
    You may not be able to make your namespace "Trait". Try changing the namespace to something else. Commented Jul 21, 2015 at 14:11
  • 1
    That was it, thank you. Make it an answer and I'll accept it. Commented Jul 21, 2015 at 14:13

1 Answer 1

12

You may not be able to make your namespace "Trait". Try changing the namespace to something else.

Sign up to request clarification or add additional context in comments.

3 Comments

Shame that this is the case. It worked but seems very silly to me and I have no idea why this limitation exists.
@Ryall I think the same. I used the namespace Mixin, however my traits are named like: ChosenNameTrait which one did you choose?
Changed namespace "Trait" to "Traits" and all work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.