Where variable constants will be present in the Symfony2 package

Maybe some will see that the question is stupid, but it is not. I ask where should Constant live in the Symfony2 Bundle, I used it in other frameworks to create variable constants in models, however, since I use Entity in Symfony2, I'm a little confused.

If it lives inside => Entity, Controller, Service or even a configuration file.

+5
source share
3 answers

I, for my part, like using Entity Constats for a simple relationship. Say, for example, you have an attribute of your object called status , which can only have values ​​between 0-2. The optional status object may be overflowed in this scenario, so I just define them as constants :

 class Entity { const STATUS_PUBLIC = 0; const STATUS_WAITING = 1; const STATUS_REJECTED = 2; } 

This allows you to simply check for status versus constants:

 $entity->getStatus() == Entity::STATUS_PUBLIC 

Or even in a branch:

 entity.status == constant('STATUS_PUBLIC', entity) 

Or in QueryBuilder :

 $builder->andWhere('status = :status') ->setParameter('status', Entity::STATUS_PUBLIC) 

It turned out to be quite effective for me.

How to avoid other answers, point to global constants. Use the options for this.


How unclear when to use Parameters :

Adapted from the official best practice :

You cannot create a configuration parameter for a value that you are never going to configure.

You can use parameters, but if these values ​​change. One example would be your application running in multiple environments. Using parameters will give you the opportunity to adapt to environmental changes without updating the code base.

+14
source

If you check out a symfony suite, like "FOSUserBundle", you will find good use and an example for this.

constant definitions :

 final class FOSUserEvents{ const CHANGE_PASSWORD_INITIALIZE = 'fos_user.change_password.edit.initialize'; 
+3
source

I don't think there is one good place to store constant variables. It rather depends on the fact that this constant variable: if it is associated with an entity, it should be an entity constant; if it is service specific, it should be a regular service.

One thing to avoid is to put constants in the configuration file unless this changes often, as described in Symfony best practices

+1
source

All Articles