dougong5817 2017-01-24 05:27
浏览 1319
已采纳

在与多个DataObject共享的配置yaml中定义的枚举列表

I have a few DataObjects that have a price tier associated to them. I could build this relationship in another DataObject however these tiers aren't going to change and I thought the best way was to define them in config.yml.

Ideally I'd like to define the DataObject like:

private static $db = array(
    'Price' => 'Enum(array("Tier 1", "Tier 2"))'
)

However I can't think of a way to do this properly in SilverStripe having a single point of maintenance like a yaml. I also thought of just making it a Varchar and checking to make sure it's in the array before setting it however this won't allow things like populating lists and so forth via the enum (probably should call the config anyway I guess). I could also just write out the array however there would be at least two places for it which would be harder to maintain.

What's the best way to do what I'm trying to achieve which is several objects referencing an array set in a single place?

  • 写回答

4条回答 默认 最新

  • dtnbjjq51949 2017-01-24 21:56
    关注

    As shown by other answers, you can accomplish that in many ways. In a project I worked on for example I have something similar to the following:

    // You need to put this into a _config.php. It copies the definition
    // of DataObject2.Field2 into DataObject1.Field1.
    $cfg = Config::inst();
    $db = $cfg->get('DataObject1', 'db');
    $db['Field1'] = $cfg->get('DataObject2', 'db')['Field2'];
    $db = $config->update('DataObject1', 'db', $db);
    

    But in my opinion the most elegant solution would be to define a new class, something like:

    class MyEnum extends Enum
    {
        /**
         * Enum values.
         * @config
         */
        private static $values;
    
        public function __construct($name = null, $default = null)
        {
            parent::__construct($name, $this->config()->get('values'), $default);
        }
    }
    

    After that you could define the values in plain YAML:

    MyEnum:
      values:
        - First
        - Second
        ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题