Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging in CodeIgniter (and MVC)

Often times I feel the need to dump a variable for debugging purpose. In CodeIgniter I am struggling to do that since I cannot simply "echo" a variable without passing it to the view first, which I think is pain-staking. I have read the official documentation, though I had found a good solution with the log_message function but cannot make it work, even though I successfully made the "logs" folder writable and changed the "threshold" as advised. Any suggestions?

https://www.codeigniter.com/user_guide/general/errors.html

like image 383
Thibaut Delarbre Avatar asked Nov 26 '12 10:11

Thibaut Delarbre


People also ask

Is CodeIgniter MVC?

CodeIgniter is based on the Model-View-Controller (MVC) development pattern. MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

Why use model in CodeIgniter?

In any application you need to call a function to retrieve some information from the database. Models responsibility is to handle all data logic and representation and load data in the views. It is stored in application/models. Look at the above snapshot, this is the basic structure of a model file.

What is controller in CodeIgniter?

A Controller is simply a class file that is named in a way that can be associated with a URI. Consider this URI: example.com/index.php/ blog / In the above example, CodeIgniter would attempt to find a controller named blog. php and load it.


1 Answers

It's not good practice, but you can output anything to the browser at any point in execution (from core classes, libraries, models and controllers) by simply using print_r() at the point you want to output the info.

Of course, this will sometimes not display as there may be redirects/routes/etc that take the user to the next step in the controller execution, but if you want to suppress this (again, for debug purposes only), you can use:

print_r($string_or_variable_to_debug);
die();

The die() command will stop all execution and leave you with just the info you want to output.

Using log_message() is better practice, but it's difficult to understand why you're not having success there if you say you've followed the following steps:

  1. Make sure that your logs folder is set to be writable
  2. Set $config['log_threshold'] to 2, 3 or 4
  3. Used the function like so: log_message('debug','Message you want to log');

If you want to use print_r() to nicely format an array or object inside the log message, then you'll need to set the second parameter of print_r() to TRUE, like so:

log_message('debug',print_r($array_or_object,TRUE));
like image 168
Jordan Harper Avatar answered Oct 31 '22 04:10

Jordan Harper