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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With