Useful hidden functions

There are some handy cake functions you might not have used or even heard of, yet.

Debugging

Most beginners use print_r() to debug variables. Without <pre> tags its really hard to read, though.
Use pr($var) or debug($var) to debug this variable and output its content. very useful inside functions, or in the view (if you don’t know what your sql result array contains, for instance).
If you are looking for a more powerful pr() function in order to display not only the content but also what type it is (int, bool, string, array, object or simply NULL), check out my returns() function in the bootstrap goodies section.

Models

save, saveField, saveAll(), deleteAll(), … return usually true/false or the record itself.
Sometimes it would be nice to know how many records have been deleted/modified.

$this->Model->getAffectedRows(); // works for INSERT, UPDATE, REPLACE or DELETE query

This will do the trick. The integer result can then be used in the flash message.

By the way: There is also ->getNumRows(); for SELECT or SHOW queries.

Logging

If you want to log certain events, you can easily use the build in functions:

CakeLog::write('geocode', 'Address \''.$address.'\' has been geocoded');

In this example every time the geocode webservice geocodes an address string, it will be logged in /tmp/logs/geocode.log. Quite handy in some cases – especially for debugging purposes.

Logging Fatal Errors as well
By default CakePHP cannot log fatal errors. They are especially helpful for finding more serious coding bugs, though.
You can easily override the shutdownFunction in your bootstrap.php

register_shutdown_function('shutdownFunction');
 
/**
 * custom shutdown function
 */
function shutDownFunction() { 
    $error = error_get_last(); 
    if ($error['type'] == 1 && class_exists('CakeLog')) { 
        CakeLog::write('error', 'Fatal Error in '.$error['file']. ' (line '.$error['line'].'):' . $error['message']);  
    } 
}

Retrieving the CakePHP version

Configure::version();

Basic Functions

What if you need to the class name and you are not sure if the plugin name is passed as well, like "Plugin.User"?
I always did this myself, until i stumbled upon the cake function for it: pluginSplit()

list($plugin, $class) = pluginSplit($name);

Other

It helps to open the core files and have a look inside. You might discover some functions you might have written yourself although it is available in the core.
Examples are string.php with tokenize() and insert() or set.php with filter(), flatten() or countDim().

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.