Skip to content

CI/CD with GitHub Actions

This guide sets up a CI/CD pipeline for an application built from this template. When it is done:

  • every push and pull request to main installs your application on a GitHub server, checks the PHP syntax, and runs your tests;
  • a failing test turns the run red and stops the pipeline before the deployment step;
  • when every test passes, the pipeline packages your application for deployment.

Before you start: complete the testing guide. composer test must pass on your computer, and your project must be pushed to a GitHub repository.

TermMeaning
WorkflowA YAML file in .github/workflows/ that describes your pipeline.
Trigger (on:)The event that starts the workflow, for example a push to main or a pull request.
JobA group of steps that runs on its own fresh virtual machine. Jobs run in parallel unless one needs another.
StepOne command (run:) or one reusable action (uses:) inside a job. If a step fails, the job stops and is marked as failed.
RunnerThe machine that runs a job. ubuntu-latest is a Linux machine provided by GitHub.
needs:Makes a job wait for another job, and skips it if that job failed. This is how a failing test stops the deployment.
ArtifactA file produced by a job (for example a zip of your application) that you can download from the run’s page.
SecretA password or token stored in the repository’s settings, never in the code. Workflows read it as ${{ secrets.NAME }}.

If your project was created from a recent version of the template, .github/workflows/ci.yml already exists: read this step to understand it, then go to Step 2.

Otherwise, create the folders .github/workflows/ in your project’s root folder (the first folder name starts with a dot), and create .github/workflows/ci.yml:

# Continuous Integration for this Slim MVC application.
# It installs the dependencies, checks the PHP syntax, and runs the PHPUnit tests
# on every push and pull request to main. A red (failed) run means a test failed.
# Extend it with a deployment job by following the CI/CD guide:
# https://ecommerce.frostybee.dev/php/ci-cd/ci/
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
name: Lint and test
runs-on: ubuntu-latest
steps:
- name: Check out the code
uses: actions/checkout@v4
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
# Same PHP version as the Dockerfile.
php-version: '8.4'
extensions: pdo_mysql, mbstring
coverage: none
- name: Cache Composer packages
uses: actions/cache@v4
with:
path: ~/.composer/cache/files
key: composer-${{ hashFiles('composer.lock') }}
restore-keys: composer-
- name: Install dependencies
run: composer install --no-interaction --no-progress --prefer-dist
- name: Create config/env.php
# env.php is not in Git (it holds passwords), so create it from the example.
run: cp config/env.example.php config/env.php
- name: Check PHP syntax
run: find app config public tests -name '*.php' -print0 | xargs -0 -n1 php -l
- name: Run the tests
run: composer test

YAML uses indentation to show structure, with spaces only (never tabs). Copy the file exactly.

What each step does:

StepPurpose
Check out the codeDownloads your repository onto the runner.
Set up PHPInstalls PHP 8.4 with the extensions the application needs. If your project needs another version, change php-version (and keep it equal to the version in your Dockerfile).
Cache Composer packagesReuses the packages downloaded by previous runs, so composer install is faster. The cache is renewed when composer.lock changes.
Install dependenciesRuns composer install, which installs the exact versions listed in composer.lock, including PHPUnit.
Create config/env.phpconfig/env.php is in .gitignore, so it is not on GitHub. Without it, the application stops.
Check PHP syntaxRuns php -l on every PHP file. A syntax error anywhere fails the run, even in a file that no test uses.
Run the testsRuns composer test. If any test fails, PHPUnit exits with an error and the step fails.

Your pipeline, your comments. Your report needs a configuration file whose comments explain each stage in your own words. Add those comments yourself, especially for the stages you add in Step 3.

  1. Commit the test setup and the workflow. composer.lock must be committed too: the runner uses it to install the same versions as your computer.
Terminal window
git add .github phpunit.xml tests composer.json composer.lock .gitignore
git commit -m "Add PHPUnit tests and CI workflow"
git push
  1. Open your repository on GitHub and click the Actions tab. A run named after your commit appears.
  2. Click the run, then the Lint and test job, to see each step’s output.

What you should see: after about one minute, a green check mark next to the run, and in the “Run the tests” step, the same OK (... tests, ... assertions) line as on your computer.

If it fails: open the red step to read its output.

OutputCauseFix
Your lock file does not contain a compatible set of packagescomposer.lock requires a newer PHP version than the workflow installs.Raise php-version in ci.yml to the version you use locally.
The lock file is not up to date with the latest changes in composer.jsonYou changed composer.json without updating the lock file.Run .\composer.bat update --lock, then commit composer.lock.
Class "App\Controllers\productsController" not found (or a similar class or file)The case of a file name does not match the code. Windows ignores it; Linux does not.See Pitfalls.
A test passes locally but fails hereThe test depends on something that exists only on your computer, such as data in your local database.Make the test create the data it needs.

A complete pipeline goes Build, Test, Deploy: the deployment must run only when the tests pass. In GitHub Actions, you add a second job with needs: test.

Choose one of the two options below and add the job at the end of ci.yml, under jobs:, at the same indentation as test:.

Option A: Package the application as a downloadable archive

Section titled “Option A: Package the application as a downloadable archive”

The job installs the production dependencies (without PHPUnit) and uploads a zip of the application as an artifact, ready to copy to a web server.

package:
name: Package for deployment
needs: test
runs-on: ubuntu-latest
steps:
- name: Check out the code
uses: actions/checkout@v4
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
- name: Install production dependencies only
run: composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist
- name: Create the release archive
run: zip -r release.zip . -x '.git/*' '.github/*' 'tests/*' 'phpunit.xml'
- name: Upload the release archive
uses: actions/upload-artifact@v4
with:
name: release
path: release.zip

After a successful run, the run’s page shows a release artifact at the bottom; click it to download the zip.

The template already has a Dockerfile. This job builds the image and publishes it to the GitHub Container Registry, from where any server with Docker can run it. It only publishes on pushes to main, not on pull requests.

docker:
name: Build and publish the Docker image
needs: test
if: github.event_name == 'push'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Check out the code
uses: actions/checkout@v4
- name: Choose the image name
# Image names must be lowercase; repository names may not be.
run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"
- name: Log in to the GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push the image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ env.IMAGE }}:latest

GITHUB_TOKEN is created automatically for each run; you do not need to add it. After a successful run, the image appears under Packages on your repository’s main page.

Check: push the change. The run’s page now shows two jobs connected by a line: Lint and test, then your deployment job.

The action versions above (@v4, @v6) were current when this guide was written. If GitHub shows a deprecation warning for one of them, update it to the version shown on the action’s page in the GitHub Marketplace ↗.

Step 4: Prove that a failing test stops the deployment

Section titled “Step 4: Prove that a failing test stops the deployment”

Your report must show a failed run in which the deployment did not happen. Produce one on purpose:

  1. Create a branch:
Terminal window
git switch -c ci-failure-demo
  1. Break a test. For example, in tests/Http/RoutesTest.php, change 404 to 200 in unknownPageReturns404().
  2. Commit and push the branch:
Terminal window
git commit -am "Demonstrate a failing test in CI"
git push -u origin ci-failure-demo
  1. On GitHub, open a pull request from ci-failure-demo to main.
  2. Open the run from the pull request’s Checks section. You should see:
    • Lint and test in red, with Failed asserting that 404 is identical to 200. in the “Run the tests” step;
    • your deployment job marked as skipped: it never ran.
  3. Take your screenshots: the run’s summary page (both jobs) and the failed step’s output.
  4. Close the pull request without merging, and delete the branch.

With Option B, the Docker job is also skipped on every pull request, because of its if: line. To show that the test is what stops it, do the demonstration on main instead (steps 2, 3 and 5 without the branch), then fix the test and push again right away.

Optional: block merging when the tests fail

Section titled “Optional: block merging when the tests fail”

In the repository’s Settings > Branches (or Settings > Rules > Rulesets), add a rule for main that requires the Lint and test status check to pass. Pull requests whose tests fail can then not be merged. Depending on your GitHub plan, this protection may only be enforced on public repositories.

If your tests use the database (see Testing your models), the runner needs its own database server. The test job can start one as a service and load your schema into it.

  1. Export your database structure and sample data from phpMyAdmin (Export, format SQL) and save the file in your repository as database/schema.sql.
  2. In ci.yml, add a services: section to the test job, at the same indentation as steps::
services:
db:
image: mariadb:11
env:
MARIADB_ROOT_PASSWORD: root
MARIADB_DATABASE: app_test
ports:
- 3306:3306
options: >-
--health-cmd="healthcheck.sh --connect --innodb_initialized"
--health-interval=10s
--health-timeout=5s
--health-retries=5
  1. Replace the “Create config/env.php” step with these two steps:
- name: Create config/env.php for the test database
run: |
cat > config/env.php <<'EOF'
<?php
return function (array $settings): array {
$settings['db']['host'] = '127.0.0.1';
$settings['db']['port'] = '3306';
$settings['db']['username'] = 'root';
$settings['db']['password'] = 'root';
$settings['db']['database'] = 'app_test';
return $settings;
};
EOF
- name: Load the database schema
run: mysql -h 127.0.0.1 -u root -proot app_test < database/schema.sql

Notes:

  • Use 127.0.0.1, not localhost. On Linux, localhost makes PDO look for a local socket file instead of the database service.
  • The root password here belongs to a temporary database that exists only during the run, so it does not need to be a secret. Real passwords (for example, for a production server) go in Settings > Secrets and variables > Actions, and the workflow reads them with ${{ secrets.NAME }}.
  • The service waits until MariaDB is ready (--health-cmd) before the steps start.

Pitfalls when moving from Windows to Linux

Section titled “Pitfalls when moving from Windows to Linux”

Your code runs on Windows locally and on Linux in CI. These differences cause most first failures:

PitfallExampleFix
File name caseThe class ProductsModel is in productsModel.php, or a view is rendered as Admin/products.php while the folder is admin/. Windows accepts it; Linux does not find the file.Make every file and folder name match its class name or path exactly, including case. To rename only the case, use git mv productsModel.php ProductsModel.php.
Missing config/env.phpThe application stops in CI.The workflow creates it (Step 1). Never commit the real env.php.
vendor/ committedHuge commits, and packages built for your computer.Keep vendor/ in .gitignore; CI runs composer install.
composer.lock not committedCI installs different versions than your computer.Commit composer.lock.
Different PHP versionsCode that uses a PHP 8.5 feature fails on PHP 8.4.Set php-version in ci.yml to the version you develop with, or avoid features newer than it.
Passwords in the workflowA production password written in ci.yml is visible to anyone who can read the repository.Store it as a secret.

A checklist for the report, in the order of the deliverable:

Tool selection and justification

  • Why GitHub Actions: your code is already on GitHub, there is nothing to install or host, it is free for this use, and actions exist for PHP and Docker.
  • Where the deployment goes (Option A: an archive for a web server; Option B: a Docker image), and why that suits your project.

Pipeline configuration and design

  • Your ci.yml, with a comment above each job and step in your own words.
  • A flowchart of the pipeline. You can draw it in draw.io, or write it in Mermaid (rendered directly by GitHub in Markdown files):
flowchart LR
A[git push / pull request] --> B[Check out code]
B --> C[Set up PHP]
C --> D[composer install]
D --> E[php -l syntax check]
E --> F[PHPUnit tests]
F -- all pass --> G[Package / build image]
F -- a test fails --> H[Stop: deployment skipped]
  • The trigger: which events start the pipeline (on:), and why.

Automated testing integration

  • How the tests are run (composer test in the “Run the tests” step).
  • The screenshots from Step 4.
  • A summary of your test classes and what each test checks. composer test -- --testdox prints every test as a readable sentence, which you can copy.

Demonstration and reflection

  • A 2 to 3 minute video or annotated screenshots of a complete green run: the commit, the Actions tab, each job, and the artifact or image.
  • Questions to guide the reflection:
    • Which failures did the pipeline catch that you would have missed otherwise?
    • What broke when the code ran on Linux for the first time, and how did you find the cause?
    • How did the pipeline change the way your team reviews and merges code?
    • What would you add next (code style checks, more tests, automatic deployment to a server)?