Symfony 最佳实践 : Where to place these constants?

标签 symfony oop model-view-controller doctrine-orm twig

我想知道,我应该在哪里放置常量,例如用于在 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/

相关文章:

symfony - 无法处理身份验证请求

javascript - JS调用没有方法的对象时调用函数

php - 哪些代码应该放在 MVC 结构中的什么地方

python - 了解 datetime 模块中 datetime 类方法的用法,而无需创建实例

javascript - 基于原型(prototype)的 OO 与基于类的 OO 相比有哪些优势?

cocoa-touch - 使用dismissModalViewControllerAnimated 不会释放任何内存

java - 使用 servlet 登录,而不是验证->重定向方式

php - 使用 Symfony2 更详细地记录错误

php - 如何在 Symfony Serializer 中反序列化对象数组?

symfony - 我如何删除 ACL(例如,当用户/对象被删除时)?