Skip to content

Instantly share code, notes, and snippets.

@ghahramani
Forked from geon/app_model.php
Last active August 29, 2015 14:08
Show Gist options
  • Save ghahramani/ed274acdc9b22a9ab5f0 to your computer and use it in GitHub Desktop.
Save ghahramani/ed274acdc9b22a9ab5f0 to your computer and use it in GitHub Desktop.

Get actual integers from MySQL with CakePHP

With this AppModel, any integer column from the database will be casted to a proper int, any time you read it from the database.

Why would I want that?

Because it's awesome to send data to the client as JSON.

json_encode() does a great job of encoding your associative arrays in PHP to JSON. But where Javascript (and hence JSON) is picky about types, PHP is more lax. That means you might end up with JSON full of "1234" instead of 1234.

On the serverside, it won't matter, most of the time, since PHP silently cast strings to integers for you. It becomes slightly more annoying when you actually want to use this data on the client, since you will probably need to convert your numeric strings to actual integers manually.

-- "But won't this be awfully slow?", I hear you asking.

You use PHP. You don't care.

Edit: I changed method of iteration for better result

<?php
class AppModel extends Model {
function afterFind($results)
{
$columnTypes = $this->getColumnTypes();
array_walk_recursive($results, array($this, "iterateRecursion"), $columnTypes);
return $results;
}
public function iterateRecursion(&$item, $key, $columnTypes)
{
if (isset($columnTypes[$key]) && $columnTypes[$key] === 'integer') {
$item = (int)$item;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment