-2

EDIT/CLARIFICATION: This question is asking where to hook the conversion into CakePHP 3.x. I know how to convert bin to hex. The question is where, in the CakePHP 3.x model structure, to intercept and change the result row(s).

I'm storing UUID data as varbinary(16) in MySQL tables. This is NOT a primary key. When I read this field, I'd like to have it converted to the standard 36-character string (binary to hex with hyphens inserted) in PHP. In CakePHP 2.x I would have used the afterFind() callback. The CakePHP 3.x documentation says to use Map/Reduce, but that would mean locating every find() in the code. It seems like I should be able to accomplish this in the model, perhaps as a CakePHP 3 Behavior.

The table looks like this:

create table `books` (
`id` int(10) unsigned not null auto_increment,
`my_uuid` varbinary(16) not null,
`created` timestamp not null default current_timestamp on update current_timestamp,
primary key (`id`),
) engine=InnoDB;

Note that I'm only asking about reading from the database. Insert and update are working fine. I'd like to convert from binary to string on read, and I think I should be doing that in the Model layer (table/entity).

ndm
  • 59,784
  • 9
  • 71
  • 110
Edward Barnard
  • 346
  • 3
  • 17
  • http://php.net/manual/en/function.bin2hex.php http://php.net/manual/en/function.substr.php – Sammitch Dec 19 '17 at 21:19
  • @Sammitch So is there a way to phrase the question to make it clear it's not about doing binary strings in PHP? It's about finding the right place to do it in CakePHP 3. – Edward Barnard Dec 19 '17 at 23:56
  • 1
    Either use a custom database type (btw, why **VAR**BINARY?), or result formatters, the latter can be applied in the models `beforeFind` event. **https://stackoverflow.com/questions/32260229/encyption-decryption-of-form-fields-in-cakephp-3** / **https://github.com/cakephp/cakephp/blob/3.5.8/src/Database/Type/BinaryType.php** – ndm Dec 20 '17 at 10:28
  • @ndm MySQL 8 documents UUID values as being stored varbinary(16): https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_bin-to-uuid – Edward Barnard Dec 20 '17 at 14:15

1 Answers1

0

A custom database type solves the situation. Follow the example at Custom data types. Thanks @ndm for the solution.

Edward Barnard
  • 346
  • 3
  • 17