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

在与多个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条)

报告相同问题?