Sunday, September 20, 2009

CakePHP slugs from MySQL unicode data

[Update] Well it seems that Cake is a bit stale on the utf-8 part. Not everyone can mod the mysql config especially on a production setup and this is actually not needed. Looks like PHPMyAdmin does good when the proper collation and server encodings are set. But it's Cake that needs an explicit 'encoding' => 'utf8' in the config/database.php file. Well I gues that the below info is still ok for when ur doing an initial setup with no legacy projects running and you're set on using utf-8 for all your future work. And why wouldn't you?

Until today I thought that PHPMyAdmin is the only one responsible for messing my romanian chars at edit. Mainly because editing from my PHP apps worked like a charm. But I just tried some Eclipse DB plugins and neither those nor my MySQLWorkbench weren't able to properly store utf-8 strings in the database. So I blamed the connection itself. Apparently this was the case because from all my tools Cake was the only one who explicitly told MySQL that they can chat only in utf-8. So I got radical on my XAMPP install and added this to my.cnf:

init_connect='SET collation_connection = utf8_general_ci'
init_connect='SET NAMES utf8'

The proper mix is not mine. It was posted on a while ago. So far all the MySQL clients seem to be happy. In case some become unhappy I'll remember to update this post.

And since we're at it I may as well tell you the full story. The app I'm working on is in romanian and the slugs Cake Inflector was giving were well, horrible. The romanian chars were not included in the replacement map and it seems that only Cake 1.3 will officially support a map of custom chars as a parameter. So since I was already using a self made TreeNavi helper (who doesn't? :) I added this to it:

function rumSlug ( $str ) {
// șȘîÎăĂâÂțȚ
$map = array(
'/ă|â/' => 'a',
'/Ă|Â/' => 'A',
'/î/' => 'i',
'/Î/' => 'I',
'/ș/' => 's',
'/Ș/' => 'S',
'/ț/' => 't',
'/Ț/' => 'T'
return preg_replace(array_keys($map), array_values($map), $str);

and used it like this:


Works just fine!


Post a Comment

<< Home