PHP Debug Tips: Divide And conquer

Todays software chains and stacks are massive and hopelessly complex. It’s completely normal to fatigue at the mere thought of setting up a proper testing environment that to allow us to develop features or bug fix unfamiliar code without getting lost in the forest. Here are some PHP-focused techniques to quickly iterate on bug fix attempts, after having broken down a complex problem into smaller chunks.

Isolate issue in a Script

Assuming, for example, we need to debug PHP regular expression against some HTML. We can dive straight into the relevant portion of the problem by sectioning it into a script when there is no need to load the entire larger CMS or Framework context.

Throw the code into a file( e.g. bug-or-feature.php ) and run it with:

 php -f bug-or-feature.php

-f <file>        Parse and execute <file>

Run interactively via CLI

PHP interactive mode works great if you wan to test run a small chunk of code, or see how some native PHP function behaves. Use php -a to drop into PHP execution environment when you want to do it live stream of consciousness style.

  -a               Run as interactive shell (requires readline extension)

Include file

To execute a file first, and then run interactively, you can use:

php -a -d auto_prepend_file=bug-or-feature.php

The-d flag allows us to apply to the “auto_prepend_file” directive:

  -d foo[=bar]     Define INI entry foo with value 'bar'

auto_prepend_file string
Specifies the name of a file that is automatically parsed before the main file. The file is included as if it was called with the require function, so include_path is used.

List of php.ini directives – Manual

Conclusion

Loading the entire context for each debugging attempt only serves to introduce more complexity and points for failure. Even in an environment with unit tests, it helps to employ additional tactics to shorten the development iteration loop. Try out these techniques to work only on the relevant part of the problem, and to hold onto your precious sanity.

0 responses to “PHP Debug Tips: Divide And conquer”