我想知道,我应该在哪里放置常量,例如用于在 Symfony 中映射状态。我习惯将它们设置在 Controller 中,但感觉不对,我更喜欢实体,但不是真的。
怎么了?
这不是“你怎么看?” - 问题,我真的很想知道 最佳实践 并感谢解释或链接来源。目前两者都有效。
Controller 或
namespace my\bundle\Controller;
class MyController {
const STATUS_NEW = 1;
const STATUs_PENDING = 2;
// ...
}
实体 ?
namespace my\bundle\Entity;
class MyEntity {
const STATUS_NEW = 1;
const STATUs_PENDING = 2;
// ...
}
Twig 中的示例:
{% set statusNew = constant('my\\bundle\\Controller\\MyController::STATUS_NEW')%} {# or \\Entity\\ #}
{% if data.status == statusNew %}
Hi, I'm new.
{% endif %}
提前致谢!
M。
最佳答案
恕我直言,实体本身是个好地方。对于 Twig 方法,在我之前的项目中,我在实体上创建了一些辅助方法来检查状态,例如:
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;
}
}
并在 Twig 中使用,例如:
{% if data.isNew %}{# more contract form: if data.new #}
Hi, I'm new.
{% endif %}
并且你不会在实体外暴露 status 字段(封装 new 的逻辑)。
希望这有帮助。
关于Symfony 最佳实践 : Where to place these constants?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790211/