samedi 8 avril 2023

Is it considered as appropriate practice to store such tiny data "records" in Model's constants instead of DB?

Working on various little/medium web projects I've noticed that it's became a usual practice for me to store some data in model's constants instead of Database, especially when such data is strongly connected to model and is critical to keep it unchanged for code to work.

For example, as shown below, when I have to store various vehicle's events (refuel, service, parking ans so on), I prefer to store theese record's TYPEs as constants instead of making a dedicated model/table for them, despite the fact that those TYPEs may have not only 'code', which would be ok to store in constants, but some extra "fields" as well (like display_name, some flags and so on), which seems more like smth that should be stored in DB.

So, the question is - what is the best bractice for such situation when it's critical to keep some data unchanged, but the data seems more like db-records then just scalar constants? What solutions/patterns are common used and considered as appropriate for such situations?

(I see that the question may seem too inparticular, but I think it would be good to gather some design patterns references here that would be useful for futher readers)

class VehicleEvents extends Model {

    public const TYPE_PARKING       = 'parking';        
    public const TYPE_WASHING       = 'washing';        
    public const TYPE_SERVICE       = 'service';        
    public const TYPE_REFUEL        = 'refuel';           
    public const TYPE_TOW           = 'tow';           

    private const TYPES_INFO = [
        self::TYPE_PARKING =>       ['display_name' => 'Парковка', 'is_regular' => true],
        self::TYPE_WASHING =>       ['display_name' => 'Мойка', 'is_regular' => true],
        self::TYPE_SERVICE =>       ['display_name' => 'Сервис', 'is_regular' => true],
        self::TYPE_REFUEL =>        ['display_name' => 'Заправка', 'is_regular' => true],
        self::TYPE_TOW =>           ['display_name' => 'Эвакуатор', 'is_regular' => false],
    ];

    public static function getTypes() {
        return array_map(fn($code) => self::getTypeInfo($code), array_keys(self::TYPES_INFO));
    }
    public static function getTypeInfo($type) {
        return array_merge(self::TYPES_INFO[$type] ?? [], ['code' => $type]);
    }

    // ...
}

Aucun commentaire:

Enregistrer un commentaire