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.
Karl Katzke