多类型字段存储逻辑优化:适配何种设计模式?
问题:字段类型专属存储逻辑的设计模式适配
数据表关联说明
现有两张数据表:entities和fields,二者的关联关系如下(Laravel模型代码):
// Entity模型 public function fields(): HasMany { return $this->hasMany(Field::class); } // Field模型 public function entity(): BelongsTo { return $this->belongsTo(Entity::class); }
fields表包含uuid、type、value字段,不同字段类型对应不同的值格式(如字符串、字符串数组、对象数组等),且存储前需要执行专属处理逻辑。
当前实现代码
目前我通过以下代码实现功能:
foreach ($request->fields as $field) { if ($field['type'] == 'regular_input_field') { // 将值以字符串形式存储 $value = $field['value']; $entity->fields()->updateOrCreate( ['uuid' => $field['uuid']], ['value' => $value], ); } if ($field['type'] == 'upload_images_field') { // 该类型字段的专属操作 // 将值以字符串数组形式存储 } if ($field['type'] == 'select_collections_field') { // 该类型字段的专属操作 // 将值以对象数组形式存储 } // 后续开发中还会新增更多不同值类型的字段 }
提问
请问该场景是否有适配的设计模式解决方案?
更新确认
经确认策略模式完全适配此场景,感谢各位。
public function __construct(string $fieldType) { $this->strategy = match ($fieldType) { 'regular_input_field' => new RegularInputFieldStrategy, 'regular_textarea_field' => new RegularTextareaFieldStrategy, // … 其他字段类型对应的策略类 }; }
内容的提问来源于stack exchange,提问作者Dmitry Uzenkov
相关产品推荐
相关产品推荐

