Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should Constant variables live in Symfony2 bundle

Maybe some will see that the question silly, however it is not.

I am asking where should Constant should live in Symfony2 Bundle, I used in other frameworks to create my constants variable in Models, however since in Symfony2 I am using Entity, I am a bit confused.

Should it live inside => Entity, Controller, Service or even config file.

like image 551
Dahab Avatar asked Apr 20 '15 08:04

Dahab


1 Answers

I for my part like using Entity Constats for simple relations. Let's say for example you have an attribute of your entity called status that can only have values between 0-2. An extra status entity might be overkill in this scenario so I simply define them as constants:

class Entity {

    const STATUS_PUBLIC = 0;
    const STATUS_WAITING = 1;
    const STATUS_REJECTED = 2;

}

It allows you to simply check for a status by comparing to constants:

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

Or even in twig:

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

Or in a QueryBuilder:

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

It has proven to be quite effective for me.

As other answers point out for global constants should definitely be avoided. Use parameters for that.


As it seems to be unclear when to use Parameters:

Taken from the official best practice:

Creating a configuration option for a value that you are never going to configure just isn't necessary.

You might consider using parameters though if these values change. One example would be your application running in multiple environments. Using parameters will give you the power to adapt to environment changes without updating your code base.

like image 76
ferdynator Avatar answered Sep 23 '22 04:09

ferdynator