Thursday, November 29, 2012

Debugging variables in Yii 

It was quite a while before I started to use this feature and now I would not be without it. As your application becomes more complex it is often necessary to see that your variables and query results are what they should be. You can even see what errors may be occurring and this is invaluable.

The first thing you need to do is configure your main configuration file. You will find this under  "Protected/config/main.php". In "main.php" you need to find a parameter called 'log' and here we use a class called "CWebLogRoute". To configure CWebLogRoute add the following
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CWebLogRoute',
'levels'=>'trace',
'categories'=>'vardump',
'showInFireBug'=>true,
),
),
),
As you can see the output is written to FireBug which is an essential tool not only for Yii but for general web development. This will also work with Chrome Developer tools  - to use it in Chrome simply click anywhere on the page and select Inspect Element and go to the Console.

To write the value of a variable to the Console in Yii all you need to do is add the following to your controller or view.
$test = array(1,2,3,4);
echo Yii::trace(CVarDumper::dumpAsString($test),'vardump');
I found this particularly useful when writing code to write data to the database. You can see if your code is successful by using:

echo Yii::trace(CVarDumper::dumpAsString($model->save()),'vardump');
If the data is written successfully to your database this will return 'true' in the console. If it returns 'false' and you are not sure why then output the errors.

echo Yii::trace(CVarDumper::dumpAsString($model->errors)),'vardump');
CWebLogRoute is absolutely invaluable in debugging Yii applications.

References:

  1. http://www.yiiframework.com/doc/api/1.1/CWebLogRoute
  2. How to log and debug variables using CWebLogRoute 

No comments: