September 3rd 2019

Store properties in JSON format and use PropertyAccess to read

Introduction

On some projects, we sometimes encounter the problem of having to store "configuration". One solution that I have encountered and / or put in place several times is to store a table in JSON format and exploit it.

This is a Prof of concept using Symfony and Mysql, it can be ported to other frameworks. There are also other more successful solutions.

Model

We define the "json" type for our property "configuration"

// App\Entity\Task

/**
 * @var array|null
 *
 * @ORM\Column(name="config", type="json", nullable=true)
 */
protected $configuration;

2 getters allow to get the complete configuration or one of its properties

// App\Entity\Task

public function getConfiguration(): array
{
    return $this->configuration ?: [];
}

  
public function getConfigurationParameter(string $parameter)  
{  
    if (null === $this->configuration) {  
       return null;  
    }  
  
    $propertyAccessor = PropertyAccess::createPropertyAccessor();  
  
    return $propertyAccessor->getValue($this->configuration, $parameter);  
}

Database

The schema of the database generated (in this case of Mysql):

CREATE TABLE `tasks` (
  `id` char(36) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:uuid)',
  `task` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `due_date` datetime NOT NULL,
  `created` datetime DEFAULT NULL,
  `config` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Note that the config property is in "json" data type (since MySQL 5.7.8, check https://dev.mysql.com/doc/refman/5.7/en/json.html)

Demo

Check this online demo (hosted on Heroku free plan, so be patient): blog-form-propertypath.herokuapp.com

the database is reset every 10 minutes

Source code

The source code is available on Github: romainnorberg/blog-form-propertypath

Feel free to leave comment

Autres language

  • Python: JSON encoder and decoder https://docs.python.org/fr/3/library/json.html

Improvement

  • Validation with Value Object or Models
  • Move to specific model/package
Romain Norberg

Romain Norberg

Php developer, play with Symfony and PhalconPhp frameworks.
More on LinkedIn or Github