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
maininstalls 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.
Key ideas
Section titled “Key ideas”| Term | Meaning |
|---|---|
| Workflow | A 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. |
| Job | A group of steps that runs on its own fresh virtual machine. Jobs run in parallel unless one needs another. |
| Step | One command (run:) or one reusable action (uses:) inside a job. If a step fails, the job stops and is marked as failed. |
| Runner | The 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. |
| Artifact | A file produced by a job (for example a zip of your application) that you can download from the run’s page. |
| Secret | A password or token stored in the repository’s settings, never in the code. Workflows read it as ${{ secrets.NAME }}. |
Step 1: Add the workflow file
Section titled “Step 1: Add the workflow file”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 testYAML uses indentation to show structure, with spaces only (never tabs). Copy the file exactly.
What each step does:
| Step | Purpose |
|---|---|
| Check out the code | Downloads your repository onto the runner. |
| Set up PHP | Installs 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 packages | Reuses the packages downloaded by previous runs, so composer install is faster. The cache is renewed when composer.lock changes. |
| Install dependencies | Runs composer install, which installs the exact versions listed in composer.lock, including PHPUnit. |
| Create config/env.php | config/env.php is in .gitignore, so it is not on GitHub. Without it, the application stops. |
| Check PHP syntax | Runs php -l on every PHP file. A syntax error anywhere fails the run, even in a file that no test uses. |
| Run the tests | Runs 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.
Step 2: Push and watch the pipeline run
Section titled “Step 2: Push and watch the pipeline run”- Commit the test setup and the workflow.
composer.lockmust be committed too: the runner uses it to install the same versions as your computer.
git add .github phpunit.xml tests composer.json composer.lock .gitignoregit commit -m "Add PHPUnit tests and CI workflow"git push- Open your repository on GitHub and click the Actions tab. A run named after your commit appears.
- 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.
| Output | Cause | Fix |
|---|---|---|
Your lock file does not contain a compatible set of packages | composer.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.json | You 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 here | The 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. |
Step 3: Add a deployment stage
Section titled “Step 3: Add a deployment stage”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.zipAfter a successful run, the run’s page shows a release artifact at the bottom; click it to download the zip.
Option B: Build a Docker image
Section titled “Option B: Build a Docker image”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 }}:latestGITHUB_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:
- Create a branch:
git switch -c ci-failure-demo- Break a test. For example, in
tests/Http/RoutesTest.php, change404to200inunknownPageReturns404(). - Commit and push the branch:
git commit -am "Demonstrate a failing test in CI"git push -u origin ci-failure-demo- On GitHub, open a pull request from
ci-failure-demotomain. - 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.
- Lint and test in red, with
- Take your screenshots: the run’s summary page (both jobs) and the failed step’s output.
- 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.
Adding a database for model tests
Section titled “Adding a database for model tests”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.
- Export your database structure and sample data from phpMyAdmin (Export, format SQL) and save the file in your repository as
database/schema.sql. - In
ci.yml, add aservices:section to thetestjob, at the same indentation assteps::
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- 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.sqlNotes:
- Use
127.0.0.1, notlocalhost. On Linux,localhostmakes PDO look for a local socket file instead of the database service. - The
rootpassword 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:
| Pitfall | Example | Fix |
|---|---|---|
| File name case | The 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.php | The application stops in CI. | The workflow creates it (Step 1). Never commit the real env.php. |
vendor/ committed | Huge commits, and packages built for your computer. | Keep vendor/ in .gitignore; CI runs composer install. |
composer.lock not committed | CI installs different versions than your computer. | Commit composer.lock. |
| Different PHP versions | Code 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 workflow | A production password written in ci.yml is visible to anyone who can read the repository. | Store it as a secret. |
Documenting your pipeline
Section titled “Documenting your pipeline”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 testin the “Run the tests” step). - The screenshots from Step 4.
- A summary of your test classes and what each test checks.
composer test -- --testdoxprints 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)?