Code automation with git hooks

Improve your code quality with git hooks, composer, and PHP Code Sniffer

First, let’s cover what all of these terms mean

Git Hooks

If you’re doing any sort of development you need to make sure that you’re using version control, and Git happens to be my preferred solution. Git offers these cool little tools called Git hooks. Hooks run bash scripts at a number of different points in the Git process and can automate a lot of really boring tasks. The hook point that we are going to use is pre-commit, which is run after you run the commit command, but before the commit is actually made. This is the perfect time to run a linting process.


Not sure that Composer really needs an introduction, but it’s used to pull in all kinds os useful tools/libraries in to your project, through the use of a composer.json file.

PHP Code Sniffer

This is a really nice tool that will compare a given file against any number of PHP coding standards.

What coding standard are we going to use?

This is really dependent on you or your company, but I’m a fan of PSR1 and PSR2. They are widely known, easily adopted, and voted on by a large number of developers.

Now to the code

It takes an unbelievably small amount of code to make this all work. We only need to create 3 files. This is what our directory structure will look like

  • project_root/
    • composer.json
    • contrib/
      • pre_commit

The first file we need is the composer.json file that tells Composer what to install, but we also take advantage of a Composer hook that runs every time the composer install  command is run, to run a bash script.

Now, we setup the contrib/ file, which is just a small bash script

And our final piece of code is the contrib/pre-commit file that checks all of our committed changes and fixes them for us automatically.

Wait, the files will fix errors automatically? Yep. Part of the PHP Code Sniffer package is PHP Code Beautifier and Fixer, which can fix many of the issues it finds automatically for you. Any that it can’t fix you’ll be notified of the exact location to go fix, and what the problem is.

Now that the files are all created, all that’s left is running a few commands to get everything working. You’ll need to SSH to wherever your site is installed, or if you’re working locally just change to the directory location in your shell application. Then you just need to run the composer install  command.

The next time you make changes to any file and go to commit that file, the linter will run and check/fix your files, then do your commit.

If you want to do this same thing with JavaScript, check out my post on using a Git hook to run JSLint.

Leave a Reply