phemellc / yii2-settings

Yii2 Settings Module
Other
151 stars 74 forks source link

add option to create entry on get() #37

Closed schmunk42 closed 7 years ago

schmunk42 commented 8 years ago

How about adding a forth parameter to get() which would create a deactivated entry, if there is no setting in the database yet?

Static helper as an example:

class Settings
{
    static function get($key, $section, $default = null, $create = true)
    {
        $value = \Yii::$app->settings->get($key, $section, $default);
        if ($value === $default && $create !== false) {
            \Yii::$app->settings->set($key, $default, $section);
            \Yii::$app->settings->deactivate($key, $section);
        }
        return $value;
    }
}

Any thoughts?

PS: I think the check should be improved a bit...

arisk commented 8 years ago

Sorry for the late reply. Generally it's not a good idea to have a get method do any kind of writes. It introduces a lot of confusion. Perhaps a new method named getOrSet?

schmunk42 commented 8 years ago

You're absolutely right with get and write!

getOrSet looks okay to me, but not 100% perfect.

What's about a "softSet", which only creates an entry when there's none, don't know a good name though. Maybe we could just start with a has method? :)

schmunk42 commented 8 years ago

Hmmm, upsert does not look right to me, at least for my use-case. But how would it differ from set?

mnglkhn commented 8 years ago

Hmm, now that I've re-read your initial post, your request is a rather specific one. Pls disregard my suggestion.

philippfrenzel commented 8 years ago

+1+