Dahab
Dahab

Reputation: 514

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.

Upvotes: 7

Views: 17226

Answers (3)

Tebe
Tebe

Reputation: 171

If you check a symfony bundle like "FOSUserBundle", you'll find some good usage and example for this.

There are constant definitions:

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

Upvotes: 4

ferdynator
ferdynator

Reputation: 6410

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.

Upvotes: 14

Tomasz Madeyski
Tomasz Madeyski

Reputation: 10890

I don't think there is one good place for storing constant variables. It rather depends on what this constant variable is about: if this is related with entity it should be a entity's constant; if this is specific to service it should be service's constant.

One thing which should be avoided is putting constants in config file unless it's going to change often as described in Symfony best practices

Upvotes: 1

Related Questions