Symfony best practise: Where to place these constants? Symfony best practise: Where to place these constants? symfony symfony

Symfony best practise: Where to place these constants?


IMHO the entity itself is a good place. For the twig approach, in my previous project, I create some helper method on the entity for check the status like :

namespace my\bundle\Entity;class MyEntity {    const STATUS_NEW     = 1;    const STATUs_PENDING = 2;    // ...   // For each const status   public function isNew(){     return $this->status == self::STATUS_NEW;   }}

and use in the twig like:

{% if data.isNew %}{# more contract form: if data.new  #}    Hi, I'm new.{% endif %}

And you don't expose the status field outside the entity (incapsulate the logic of new).

Hope this help.


The answer is it depends, but there are now Symfony best practices; in particular there is a section on constants vs. configuration options that speaks to exactly what you're asking.

Use constants to define configuration options that rarely change.

The nice thing about defining constants in classes is that you can easily access them in Twig. For instance, if you have a Post class like the example in the best practices, and pass an instance of that as post to your template, you can access the constant via:

{{ constant('NUM_ITEMS', post) }}

Now, there are definitely times where you might want to specify configurable options - say if you're creating a reusable bundle and want to allow an override of these values. So again it depends, but for your case, Symfony recommends placing them in your entity.


The STATUS constants belong in the entity so that they can be reused in multiple contexts (multiple controllers, for example) without needing to redefine the constants in each controller.