Categories
Programming & Web Development

PHP Debugging with Xdebug

https://i2.wp.com/xdebug.org/images/xdebug.gif?w=580

Web development with PHP can get frustrating without the adequate tools. The most common thing a new web developer does when attempting PHP debugging is to add var_dump() calls to print out the value of a variable at a certain point in the program’s execution, in conjunction with an exit() or die() call.

Doing this will reveal the values of the variable you’re trying to check, but it requires you to add and remove lines in your code, and more often than not, those lines are forgotten to be removed, so they end up as bugs in the code.

A good way to develop your code is with test driven development, using unit tests to verify the output of your methods. But sometimes there are parts of the code that cannot be easily tested. For these cases using a proper step by step debugger is a better tool for the job. Xdebug is a PHP extension that does the job. With Xdebug you can set breakpoints in your code, display the contents of constants like $_POST and $_SESSION, give you a trace of the execution around the breakpoint or uncaught exception, and follow the values of any variables you want. You can also profile your application to detect performance bottlenecks.

There are several ways to install Xdebug on your development system. On a Debian-based system you install it with the following command:

sudo aptitude install php5-xdebug

For other systems and custom installations there is an installation Wizard, following the steps in the page will provide you with the instructions needed for your particular case.

Then check your php.ini file to configure the Xdebug extension to your liking. Check the documentation for all the features and options. Here’s a sample of the options:

xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_mode=req
xdebug.idekey=default
xdebug.remote_log="/var/log/xdebug/xdebug.log"
xdebug.show_exception_trace=0
xdebug.show_local_vars=9
xdebug.var_display_max_depth=10
xdebug.show_mem_delta=0
xdebug.trace_format=0
xdebug.profiler_enable=1
xdebug.profiler_output_dir="/tmp/xdebug/"

The option xdebug.show_local_vars will display the number of local variables available at the breakpoint, so no need of several var_dump() calls for each variable you want to see. The xdebug.var_display_max_depth changes how many nested levels of arrays or objects will be displayed, where by default, var_dump() will only display 3 levels down. There are more interesting data display options in the documentation.

Make sure the remote log directory and profiler output directories exist in your system. Restart your web server and you’re good to go.

Your phpinfo() output page should now display a section like this:

file:////home/gabriel/xdebug_info.png

Now, here are some links to setup and use your development environment with Xdebug, depending on what you use.

Hope this helps and happy coding!

Categories
GNU/Linux Free Software & Open Source Programming & Web Development

10 PHP code quality tools to avoid a mess in your projects

img_2052

When programming in any language there are certain common errors that everyone makes as they mature and evolve their programming skills. In the case of PHP, I’ve seen a lot of ugly and complicated code around, since the language is very permissive.

To have a good and healthy PHP code base so it won’t resemble the unmanageable cabling mess in the picture above, your project needs to have the following:

– no spaghetti code
– code reuse (avoid code repetition)
– avoid complicated nested loops
– Encapsulation (organize code in classes)
– Clean user I/O
– Code Documentation
– Consistent code conventions
– Tests

Luckily there are some PHP code quality tools that can help us address most of these problems and give us a diagnostic of our project’s code health.

###Documenting your code

PHP Documentor: Documenting code with PHP Documentor is very simple and easy. You just need to follow a very simple markup before your functions and classes and the tool will generate all the developer documentation for you. It’s also very handy when adding new people to your project or inheriting someone else’s work. Just by seeing the documentation comments in the code you can understand what a given function does, what each of its parameters need to be and what it returns. You can also expand the documentation to add use cases and even unit tests!

###Code consistency

PHP Code Sniffer: A tool that analyses the syntax of your project’s code based on a PHP syntax standard. Known standards like PEAR or Zend syntax styles are included by default but you can also customize and define our own team’s style.

PHP Depend
Analyzes the code for common issues and potential optimizations. Some examples of those are:

– if your function is too long
– if your function has too many parameters
– variable names too long or too short
– too many nested cycles
– use of eval()
– name convention consistency
– unused methods or variables

PHP Mess detector: A fork of PHPDepend with a friendlier UI and configuration options

PHPCPD (Copy/Paste Detector): A tool that will detect copy/pasted code across your project that can be reused.

###Testing

Unit testing

PHP Unit and Simpletest: Unit testing has been very useful in my experience on recent projects where I’ve been allowed to implement it. On personal project I always tend to do unit testing before layout out all my code. It might take more time to develop your project at the beginning but it will save you tons of time debugging and tracing back errors when you think you’re done programming.

If you’re using Ubuntu and have problems running PHPUnit, here’s a post about how to solve the problem.

Here’s a quick guide on how to start using Simpletest.

Integration Testing (browser emulation)

Mink and Behat are the tools you’ll need to do browser emulation to test your interfaces and how it’s all put together and interacting for the user.

###Put it all together with Phing

Phing is a tool like GNU Make or Apache Ant but it’s in PHP and extensible via PHP classes. You can put all of these tools together with Phing, so you can automate all the checking, testing and even deployment and cleanup of files or databases.

With these tools you can have a very robust quality assurance workflow on your project. Of course, this doesn’t mean that there’s not going to be any bugs or that your project will have the best code, but at least it will reduce very common problems, will increase code maintainability and help you spot problems easier. The transitions from adding or removing people from the project (like in large teams or dynamic organizations) will be smoother, as well. Also those transitions will be even smoother if you consider using an established web framework for your project instead of writing your own.

I gave a talk at FSL Vallarta 2012 about this, you can download the slides for the talk “Herramientas de calidad en codigo PHP” here. (slides in Spanish)

Categories
Programming & Web Development Tutorials & Tips

Using Git with Subversion repository subdirectory

Git logo

Interacting a local git repository with a subversion one has been very useful and is very common on old projects. The way to do that is by using the git svn commands. But sometimes there are situations where there is one large repository with several projects as subfolders in that repo.

Using the standard svn cloning command:

git clone my_svn_repo_server.com/repository

Will checkout the whole SVN repository (all subfolders, hence, all projects) into your local machine. This can be very large if the codebase and history is big, and very slow to interact with, since getting your local repository updated will involve getting changes from all other projects.

To make git clone a subdirectory from an SVN repository, use the following:

git svn init http://my_svn_server.com/repository/path/to/directory/of/project
git svn fetch

This way you not only clone that subdirectory, but also you will get updates from only that folder, making faster code pulls and pushes to the central SVN repository.

While I consider a very bad practice to have one large Subversion repository with several projects inside it as subfolders, I’ve come across such setups several times and it drove me crazy to have to checkout the whole thing. Hope this helps out.

Categories
Emacs GNU/Linux Free Software & Open Source Programming & Web Development

Easy CSS editing with Emacs

Editing CSS in Emacs is very easy since the standard CSS mode comes included by default. But developer Julien Danjou created this nice minor mode called rainbow-mode which will display the color of the code as the background of the code’s text. It is very useful to immediately see the colors right there in the style sheet instead of trying to remember each code and then test in the browser window.

One of the problems I had was when opening any CSS file, it would open by default css-mode, but I had to manually load rainbow-mode every time. The elisp function auto-mode-alist is used to detect a file type by its name and running a function associated with it, generally the function to enable a major mode to edit that type of file. For minor modes I couldn’t find anything that would allow me to launch them without inhibiting the mayor mode’s startup.

So since auto-mode-alist takes a regular expression for the file type and only one function as its arguments, I wrote a function that will run both and use that as the second argument to execute.

;; CSS and Rainbow modes 
(defun all-css-modes() (css-mode) (rainbow-mode)) 

;; Load both major and minor modes in one call based on file type 
(add-to-list 'auto-mode-alist '("\\.css$" . all-css-modes)) 

Hope you find it useful and you like the combination of css-mode and rainbow-mode as much as I do.

Categories
Bookmarks Programming & Web Development

From my reading links: HTML5 forms and Django, Google API playground and Python development tips

  • Making Forms fabulous with html5 Great introduction to the new HTML5 form input types and what you can do with them.
  • HTML5 – Example Form validation and styling Form elements With the new HTML5 form input types and CSS3 properties, form validation is very quick and easy, as well as nice form element presentation.
  • Head JS A very interesting utility that will load all your js scripts (jquery, google analytics, etc) in parallel so page load times get shorter, plus a lot of other nice features like new HTML5 elements styling in browsers that don’t yet support them like some versions of Internet Explorer.
  • Google APIs code playgroud I didn’t know you could play with all the Google APIs in a single webpage, testing your code as your write it.
  • GeoDjango and google maps An interesting read if you’re trying to integrate Google Maps with Django
  • HTML5 and Django form inputs How to render the new HTML5 input types with Django form classes. It doesn’t require much, really easy and fast.
  • Emacs as Python IDE A bunch of tips to have a good Emacs Python development environment. I personally don’t prefer IDEs, so I don’t use ECB but the rest is very useful.
  • Setting up a Python Environment Good advice for those coming from a PHP world and are getting started on Python development. I didn’t know about virtualenv until I had to deploy my first Django app on a shared host web server. Then it all made sense.
Categories
GNU/Linux Free Software & Open Source Programming & Web Development

The importance of Web frameworks in startup development teams

SPNP #52

In a start-up environment, things happen so fast that there’s very little time to polish your tools. Code gets done undocumented, development team members come and go with different programming styles and tools, and the chaos just builds up as the business goes.

At some point, you can’t finish or maintain something because one team member left the company with the knowledge of the code and without documenting. You either have to spend time figuring out what was done and how it works, or rewrite all that unmanageable code. I’ve seen this scenario happen too many times.

Just as the saying goes: “Stand in the shoulders of giants”, using an open source development framework is essential for the following reasons:

– Access to lots of documentation, tutorials, forums, etc
– Proven working code by a large user community
– Everyone knows where to look when a certain change is needed
– Development teams scale faster because new hires or people switching project teams can catch up and integrate to the team quickly
– Benefit from patches and upgrades from outside your development team
– Improve team productivity by not having to spend time writing basic common components from scratch every time

Even when using a closed source framework, you still get most of the benefits. Some companies prefer to build their own tools and frameworks. This approach will work out as long as they stay consistent and everybody agrees to use them in a standard way. But unless you’re addressing a very specific problem or facing a special situation, I recommend you not to reinvent the wheel and use one of the many existing open source development frameworks out there.

Here’s an old video of a chat with Steve Jobs, where he talks on how to improve productivity and saving time and resources in a development team, by eliminating lines of code to write and taking advantage of what is already out there.

Photo: SPNP #52 is Creative Commons by J_P_D on Flickr