php - Doctrine 2 实体中的常量

标签 php constants doctrine-orm

假设我有以下 Doctrine 2 实体:

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     *
     * @var int
     */
    protected $id;

    /**
     * @ORM\Column(length=100)
     *
     * @var string
     */
    protected $name;

    /**
     * @ORM\Column(type="integer")
     *
     * @var int
     */
    protected $status;
}

用户可以有多种状态,例如:Pending、Active、Suspended。整个代码(服务、存储库等)和 UI 层都需要这些状态(用户编辑表单将在下拉列表中显示它们)。

为了避免在多个地方定义它们,到目前为止我所做的是使用一个类来保存它们(所有应用程序的常量),它看起来有点像这样:

class App_Constants extends Zrzr_Constants
{

    protected static $_constants = array( 
        'users' => array( 
            'status' => array( 
                0 => 'Pending', 
                1 => 'Active',
                2 => 'Suspended' ) ) );

}

基类 (Zrzr_Constants) 会提供一些方法来检索它们,它看起来像这样:

class Zrzr_Constants
{
    protected static $_constants = array();

    public static function getConstantValues( $key, $subkey )
    {
        // ...
    }

    public static function getConstantByName( $name )
    {
        // ...
    }
}

常见的用法是:

// example of retrieval by constant name ... it would return an integer
$pendingStatus = App_Constants::getConstantByName( 'USERS.STATUS.PENDING' );

// example of retrieval for UI display purposes ... would return an array
$statuses = App_Constants::getConstantValues('users', 'status');

当然这意味着存在一些限制,因为常量标签不能包含点,但我可以接受。

然而,使用 Doctrine 2 并采用 DDD 方式,告诉我“状态”字段实际上应该是一个“值对象”(但 Doctrine 2 尚不支持值对象),或者至少我应该拥有实体内定义的常量(使用 const)。

我的问题是我该怎么做才能避免不断地重新定义 UI 层?我需要通过名称(在代码中)访问常量,并在 UI 下拉列表的情况下(例如)拥有此类字段的所有可能值。

最佳答案

我想,你可以这样做:

class User {
  const STATUS_PENDING = 'Pending';
  const STATUS_ACTIVE = 'Active';
  const STATUS_SUSPENDED = 'Suspended';

  public static function getStatusList() {
    return array(
                 self::STATUS_PENDING, 
                 self::STATUS_ACTIVE, 
                 self::STATUS_SUSPENDED
                );
  }

  public function getStatus() {...}

  public function setStatus($value) {...}

  public function isStatusPending() {...} //If you need it
}

在 UI 层,您可以使用本地化服务获取状态的文本版本(如果状态常量是数字,UI 层可以通过添加前缀将它们转换为字符串,例如 user_status_0)。在 Symfony2 View 中,您可以使用 trans Twig 过滤器从 user 本地化域获取用户状态的文本版本。

如果您的网站只使用一种语言,那么我认为 User::STATUS_XXX 就可以了。我认为您不应该通过创建一个新类来保存用户状态而使问题过于复杂。

如果您最终会有很多状态或其他一些相关的东西,我认为您将不得不为它们创建一个单独的实体。

关于php - Doctrine 2 实体中的常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6898563/

相关文章:

symfony - 错误 : Invalid PathExpression. 必须是 SingleValuedAssociationField。在教义2中

php - Doctrine - 与实体分离的模型

php - 如何根据日期计算独立访问次数

php - 当包含来自远程服务器的 PHP 文件时,常量不是 "populated"

c++ - 初始化类的常量字符指针

javascript - Rollup,多个文件,多个文件中相同的常量名称: error in browser: Uncaught SyntaxError: Identifier 'o' has already been declared

php - Doctrine2 DBAL 的良好替代 DBAL

php - jquery 甘特图插件

javascript - 如何调用HasOffers中的Api并建立服务器和客户端的连接

php - PHP 与 Pylons 的基准测试