No domain? No problems! Fallback translations in CakePHP
A common methodology in CakePHP is that if something doesn’t exist somewhere, it will look in the next logical spot until it finds it. This is evident with themed views, controllers, models, basically everything in the framework. That’s why I was a little bit suprised dismorning when I was looking into translations within a domain. If the phrase didn’t exist in the domain then it would simply return the original string, without looking inside the default domain.
So I came up with a function that would first look inside the custom domain and if nothing was found then it would naturally work inside the default domain. The function is named __dd(), which is short for default domain.
/** * Allows you to override the current domain for a single message lookup. * If the msg doesn't exist in the current domain, it will use the default * domain. * * @param string $domain Domain * @param string $msg String to translate * @param string $return true to return, false to echo * @return translated string if $return is false string will be echoed */ function __dd($domain, $msg, $return = false) { $d = __d($domain, $msg, true); if ( $d == $msg ) { return __($msg, $return); } if ( $return ) { return $d; } else { echo $d; } }
I’m not sure why the CakePHP gods haven’t done it this way, I’m pretty sure there would be a reason though. The idea came to me with the recent feature addition of domains to my settings plugin (documentation).