Printing Debug Messages

Perch’s debug mode allows you, the developer, to get contextual debug messages whether that is on the front-end of your site or in the control panel.

Learn how to turn on Perch’s Debug Mode

So when you have a complex page or you are writing an add-on (app, template filter, dashboard widget, etc) it makes sense to make use of Perch’s debugging system.

To add a debug message:

PerchUtil::debug('This is a regular debug message.');

You can highlight a debug message as a notice to indicate that something may have gone wrong, but everything else will probably still work. You do that by adding notice as the second parameter:

PerchUtil::debug('Expected to find some records. None found.', 'notice');

Similarly you can add an error message:

PerchUtil::debug('Something went wrong!!', 'error');

A simplified example:

if(isset($product['price'])) {
    echo $product['price'];
} else {
    PerchUtil::debug('Product has no price set.', 'notice');
}

If you are building a Perch app, it may be a good idea to prefix your debug messages so they are easier to locate and won’t be mistaken for another app’s debug messages:

PerchUtil::debug('App Name: could not save submitted data.', 'error');

You can also mark debug messages with PerchUtil::mark():

PerchUtil::mark('Some message');

Arrays and Objects

Sometimes it’s useful to output an array or an object to the page to check its content. This can be done in more than one way in PHP. One way to do it:

echo '<pre>';
print_r($array);
echo '</pre>';

Or if you prefer a one-liner:

echo '<pre>' . print_r($array, 1) . '<pre>';

In Perch sometimes you skip the template processing and use the returned data in PHP. When you skip template processing, you get an array. Checking the content of that array can be helpful:

$article = perch_blog_custom([
    'filter' => 'postSlug',
    'match' => 'eq',
    'value' => perch_get('s'),
    'skip-template' => true,
]);

echo '<pre>' . print_r($article, 1) . '<pre>';

The problems with outputting the array this way is that:

You can use PerchUtil::debug() to output the array in the debug message at the bottom of the page:

PerchUtil::debug($article);
link