dimanche 5 mars 2023

Is there a design pattern for such a thing?

There are 2 tables: entities and fields with the relations:

// Entity
public function fields(): HasMany
{
  return $this->hasMany(Field::class);
}

//Field
public function entity(): BelongsTo
{
  return $this->belongsTo(Entity::class);
}

A field has uuid, type, value columns. Each field type has its own value format (e.g. string, array of strings, array of objects, etc.) with its own logic before saving the value.

I've managed to do it work with the following code:

foreach ($request->fields as $field) {

  if ($field['type'] == 'regular_input_field') {
    // save value as string

    $value = $field['value'];

    $entity->fields()->updateOrCreate(
      ['uuid' => $field['uuid']],
      ['value' => $value],
    );
  }

  if ($field['type'] == 'upload_images_field') {
    // some unique operations for this type of field
    // save value as array of strings
  }

  if ($field['type'] == 'select_collections_field') {
    // some unique operations for this type of field
    // save value as array of objects
  }

  // additional fields with different value types will be added during the development

}

Does anyone know if this situation has some design pattern solution that can be used here?

Aucun commentaire:

Enregistrer un commentaire