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条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序