How I use Git hooks to enforce PHP standards

My rule is simple: a code standard that depends on someone remembering it will eventually be forgotten. In PHP projects, I use Git hooks to turn formatting, syntax and project conventions into a quick local check before changes reach a pull request.

The hook has to be fast. A pre-commit check that takes a coffee break teaches developers to bypass it. That matters for teams spread across Sydney, Melbourne and Brisbane, where client support can interrupt an afternoon coding session.

I treat hooks as an early-warning system, not a replacement for continuous integration. CI runs the complete suite in a clean environment; the local hook simply delivers the first useful result while the code is still in front of the developer.

Make the hook the quickest feedback loop

I start by choosing one fast command, usually a Composer script that checks PHP syntax and runs the configured style tool. If the command cannot finish in roughly ten seconds, I move part of it to a pre-push hook instead of making the commit unpleasant.

During a focused coding block, I also block noisy notifications using this blocking distractions guide. A quiet machine and a fast hook serve the same purpose: both protect the short interval in which a developer is likely to act on a failure.

A good error message names the file, the rule and the repair command. It should exit non-zero so Git stops the commit while avoiding a wall of output copied from three different tools. One clear failure is easier to trust and fix.

Store the hooks with the project

Git does not version .git/hooks by default, so I keep executable scripts in a repository directory such as .githooks/ and point each clone at it with git config core.hooksPath .githooks. The setting itself is local, so the setup step must be repeatable.

I document that command and automate it in the project bootstrap script. On Unix-like systems, the hook also needs its executable bit set; on Windows, the shell wrapper can call PHP directly. The underlying PHP logic remains portable across macOS, Linux and Git for Windows.

Putting the scripts in source control makes review possible and stops hook behaviour from depending on whichever engineer last touched the repository. It also allows CI to run the same scripts instead of maintaining a private collection of shell aliases on one laptop.

Inspect staged PHP files

The pre-commit hook should inspect the index, not every file in the working tree. I obtain staged additions, copies, modifications and renames with git diff --cached --name-only --diff-filter=ACMR -z -- '*.php', then pass that null-delimited list to the checker. This avoids linting unchanged files.

PHP_CodeSniffer works well for per-file rules, while PHP-CS-Fixer can apply a project configuration in dry-run mode. I expose them through Composer so developers do not need to remember paths or flags. Generated code, vendor/ and build artefacts are excluded through each tool’s own configuration.

I prefer a dry-run failure to an automatic rewrite inside the hook. A fixer that changes the working tree after Git has staged the original content creates a confusing partial commit. The hook can tell the developer to run the repair command, review it and stage the result.

Keep deeper checks in their own lane

Formatting and syntax fit the pre-commit stage because they are quick and local. PHPStan or Psalm often needs the full project to resolve types, and the test suite may take minutes, so I place those checks in a pre-push hook or leave them to CI. This keeps the local gate credible.

For an API service, static rules can confirm that middleware is wired in, but they cannot prove the service handles a traffic burst correctly. Runtime controls such as API rate limiting middleware still need their own tests, and the same principle applies to queues, caches and database transactions.

My pre-push hook runs the same Composer commands used by CI, including the analyser and focused tests. CI remains the final authority because it catches an omitted hook, an unsupported PHP version and differences in extensions or environment variables.

Handle the awkward cases

Hooks are ordinary programs, so they can be skipped with --no-verify; that is why merge protection should require CI rather than trust a local event. I keep the emergency bypass documented for broken workstations, but never treat it as the normal path. Repository and branch protections stay enabled.

Generated clients, migration snapshots and cached artefacts often fail style checks for good reasons. Rather than adding broad exclusions, I exclude known paths in the linter configuration and document why each one is safe. I also test the hook after rebases, merges and a clean checkout.

Line endings and PHP versions can make a locally green check fail elsewhere. I pin supported versions in composer.json, commit the formatting configuration and let CI exercise the oldest supported release. That is more reliable than asking every developer to reproduce the entire production matrix by hand.

Fit the workflow to Australian teams

Small Australian consultancies often need one workflow across several client teams. A Brisbane developer may move between a Sydney agency and a Canberra public-sector project, where procurement and security requirements reward repeatable evidence. Checked-in hooks give each setting the same starting point without replacing the client’s formal controls.

Local conventions can stay local without making code inconsistent. I use Australian English such as “organisation” and “behaviour” in documentation and user-facing copy, while code identifiers and API names follow the agreed project standard. During an afternoon sanity check—what an Australian team may call an arvo review—the formatter handles mechanical spelling and layout.

  • Run PHP syntax checks and configured style rules against staged PHP files.
  • Keep pre-commit feedback within ten seconds and move slow analysis elsewhere.
  • Use the same Composer commands for local checks, pre-push checks and CI.
  • Exclude vendor, generated and build paths explicitly, with a reason recorded.
  • Check Australian English in prose without renaming stable code identifiers.
  • Require successful CI before merge, even when a developer skips a local hook.

When a small office needs a standard test machine, I refer to my hardware vendors notes before recommending PHP versions or storage. Consistent documentation and hooks help, but they cannot compensate for unsupported runtime combinations.

Put the first gate in place

I roll this out on a branch, beginning with syntax and formatting because those failures are easy to understand. I ask the team to commit a known violation, confirm the hook blocks it, repair the file and commit again. That small rehearsal exposes permission and path problems before everyone changes workflow.

After a fortnight, I review how often hooks are bypassed and where they slow people down. Persistent bypasses usually mean the rule is noisy, the fix is unclear or the check belongs in CI. I adjust the policy based on evidence, then share the final Composer commands in the project README.

Start with one repository this week: add the staged-file pre-commit check, confirm it on a deliberate mistake and keep the hook small enough that every clean commit feels quicker than the review it prevents. Then extend the same pattern to the rest of your PHP projects.

Experience

Information Technology Consulting

Independent Practice

Provides IT consulting services focused on infrastructure planning, cloud migration strategy, and systems architecture. Engagements draw on years of hands-on sysadmin and development experience across Linux, Windows, and hybrid environments.

K9 Search & Rescue Volunteer

Ongoing

Active participant in K9 Search & Rescue operations, combining technical logistics skills with field support for canine search teams.

Karl Katzke's Blog

October 2006 – May 2014

Published a long-running personal technology blog covering cloud vs. in-house infrastructure, F# and Mono on OSX, hardware vendor critiques, RAID card performance analysis, and sysadmin storytelling. Notable posts include "When Sysadmins Ruled the Earth" (May 15, 2014) and "Getting Started with F# and Mono on OSX" (December 22, 2012).

Credentials

A small badge icon with a shield shape in muted blue tones on a light background

Systems Administration

Deep experience with Linux (RHEL, SLES, CentOS), high-availability clusters, and STONITH configurations.

A small badge icon with a gear shape in muted blue tones on a light background

Cloud Infrastructure

Practical knowledge of AWS EC2, reserved instances, and cost analysis for cloud vs. on-premises deployments.

A small badge icon with a code symbol in muted blue tones on a light background

Development

Proficient in F#, PHP (Symfony), and cross-platform tooling including Mono and MonoDevelop on OSX.

Studies

F# & Functional Programming

Self-directed, 2012

Explored strongly typed functional programming with F# on OSX using the Mono runtime. Published a detailed getting-started guide covering toolchain setup and cross-platform game development research.

High-Availability & Cluster Management

Professional Development, 2009

Configured and documented crm_mon email alerting for STONITH events on SLES11-HAE clusters, integrating with Nagios monitoring for production environments.

Hardware & Storage Performance

Ongoing

Conducted hands-on benchmarking of SATA/SAS RAID controllers including HighPoint RocketRaid 2740 and LSI/SuperMicro AOC-USASLP2-H8iR, comparing against software RAID configurations.

Skills

A small icon representing a server with clean geometric lines in slate blue

Linux Administration

RHEL, SLES, CentOS — package management, kernel tuning, HA clustering, and monitoring integration.

A small icon representing a cloud shape with clean geometric lines in slate blue

Cloud Architecture

AWS EC2, reserved-instance planning, cost modeling, and hybrid infrastructure strategy.

A small icon representing code brackets with clean geometric lines in slate blue

F# & .NET/Mono

Functional programming on OSX, MonoDevelop toolchain, and cross-platform game-dev exploration.

A small icon representing a database cylinder with clean geometric lines in slate blue

PHP & Symfony

Web application development with the Symfony framework and the broader PHP ecosystem.

A small icon representing a storage drive with clean geometric lines in slate blue

Storage & RAID

SATA/SAS controller evaluation, md RAID configuration, and performance benchmarking.

A small icon representing a shield with clean geometric lines in slate blue

High Availability

Pacemaker, STONITH, crm_mon alerting, and Nagios integration for production cluster monitoring.