Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony best practise: Where to place these constants?

I'm wondering, where I should place constants, e.g. for mapping a status, in Symfony. I'm used to set them in a controller, but it doesn't feel right and I prefer the entity, but not really.

What's right?

It's not a "what do you think?"-Question, I really want to know the best-practise and appreciate explanation or linked source(s). Both work, for now.

Controller or

namespace my\bundle\Controller;

class MyController {
    const STATUS_NEW     = 1;
    const STATUs_PENDING = 2;
    // ...
}

Entity ?

namespace my\bundle\Entity;

class MyEntity {
    const STATUS_NEW     = 1;
    const STATUs_PENDING = 2;
    // ...
}

Example in twig:

{% set statusNew = constant('my\\bundle\\Controller\\MyController::STATUS_NEW')%} {# or \\Entity\\ #}
{% if data.status == statusNew %}
    Hi, I'm new.
{% endif %}

Thanks in advance!

M.

like image 251
Mr. B. Avatar asked Dec 11 '22 01:12

Mr. B.


1 Answers

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.

like image 166
Matteo Avatar answered Dec 30 '22 04:12

Matteo