Doctrine array vs simple_array vs json_array

0x1gene picture 0x1gene · May 16, 2013 · Viewed 59.2k times · Source

I am using symfony and doctrine as my ORM.

For available types I have:

  • array
  • simple_array
  • json_array

I am wondering what the difference is between each of them: when do I use one or the other?

Can I have a demonstration for each of them to illustrate the differences?

I already use simple_array in some applications but I find I don't understand formType... (Or maybe I'm not using it well!? )

To illustrate my question, here is an example:

I have an Task that I have to run on specific days So I created TaskEntity with days attribute

Days would be:

$days = array(
    1=>true,
    2=>true,
    3=>true,
    4=>true,
    5=>true,
    6=>false,
    7=>false
);

But I have no idea which of the above types to choose ...

Answer

Marino Di Clemente picture Marino Di Clemente · May 16, 2013

For your problem simple_array is the right way, the right way may also create seven boolean fields.

However here's a little vademecum:

The best way to see how a type works in doctrine is to read the code of the type, this is because there are several details that are taken for granted or are not really explained in the documentation.

So you can go into

/vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/Type.php

find your type and check if its methods work as you want.

Here some details:

simple_array

in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/SimpleArrayType.php

return implode(',', $value);

it's just a implode()/explode() of items, stores only the values and it's useful because you can easily query the database.

array

in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/ArrayType.php

return serialize($value);

calls PHP to serialize()/unserialize(), it's faster than json_array. Looking at the code I think it also works with objects. Obviously if you see the field as plain text it's uncomprensible.

json_array

in /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/JsonArrayType.php

return json_encode($value);

it calls json_encode()/json_decode(), if you look in the field you can see a unformatted JSON array but it's more readable than PHP's serialized object and is really more portable (JSON exists everywhere).

June 2018 update

  • now there is a complete and more updated documentation here
  • json_array is deprecated in favor of json type, it will leverage on new database features for json fields