Use traits in Symfony

Hello,

Today, I'm going to show you how to make the most of Traits on Symfony.

First, What is a OOP trait?

From PHP offical documentation about Trait:

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way.

An example of a trait and the particular syntax:

trait Something {
    public function do() {
        echo "I have done";    
    }
}
class SomeElse {
    use Something;

    public function doAnother() {
        $this->do();
        // output "I have done"
    }
}

Imagine now that we want, in several Symfony controllers, to make some methods available, here to restrict access to some of the code:

trait ControllerTrait 
{
    protected function handleAccess(User $user, Cercle $cercle)
    {
        if (! $this->hasAccess($user, $cercle))
        {
            throw new AccessDeniedException();
        }
    }

    protected function hasAccess(User $user, Cercle $cercle)
    {
        $cercle_manager = $this->get('cercle_manager');
        return $cercle_manager->findByCercleUser($cercle, $user) !== null;
    }
}
class CercleController extends Controller
{
    use ControllerTrait;

     /**
     * @Route("/groupe/index/{slug}", defaults={"slug" = null}, name="groupe_index")
     */
    public function indexAction(Request $request)
    {
        $slug = $request->get('slug');
        $cercle = $this->getCercle($slug);
        $user = $this->getUser();
        $this->handleAccess($user, $cercle);
        // More stuff
    }
}

Another idea to using Traits in Doctrine definition entities, in order to make some features common, like Translatable, Timestampable, Sluggable...

Bests Regard,

Weenesta