Composer, autoloading and testing
Professional PHP projects share three tools: Composer to install packages and load classes automatically, PSR standards so code from different authors fits together, and PHPUnit (or Pest) for automated tests. This lesson builds a small, properly structured project with all three.
💡 Composer downloads packages from the internet, which the in-browser editor can't do. The examples are terminal commands, and every output shown was produced by running them with PHP 8.5 and Composer 2.
Composer
Composer is PHP's package manager. Packages come from packagist.org, which lists over 400,000 of them. Start a project:
mkdir -p shop && cd shop
composer --version 2>/dev/null | head -1 | cut -d' ' -f1-3
composer init --name=asha/shop --type=project --autoload=src/ --no-interaction > /dev/null
cat composer.jsonComposer version 2.11.2
Writing ./composer.json
PSR-4 autoloading configured. Use "namespace Asha\Shop;" in src/
Include the Composer autoloader with: require 'vendor/autoload.php';
{
"name": "asha/shop",
"type": "project",
"autoload": {
"psr-4": {
"Asha\\Shop\\": "src/"
}
},
"require": {}
}--autoload=src/ set up PSR-4 autoloading: classes in the Asha\Shop namespace are loaded from the src/ folder.
Installing packages
cd shop
composer require brick/money --no-interaction --quiet
composer require --dev phpunit/phpunit:^12 --no-interaction --quiet
composer show --direct | awk '{ print $1, $2 }'
lsbrick/money 0.15.2 phpunit/phpunit 12.5.45 composer.json composer.lock src vendor
| File / folder | Purpose | Commit to Git? |
|---|---|---|
composer.json |
Your dependencies and their allowed versions | Yes |
composer.lock |
The exact versions installed | Yes (for applications) |
vendor/ |
The installed packages and the autoloader | No (add to .gitignore) |
On another machine (or a server), composer install installs exactly the locked versions. composer update upgrades within the allowed ranges and rewrites the lock file. --dev packages (like PHPUnit) are only needed during development: deploy with composer install --no-dev.
Version constraints work like Ruby's and npm's: ^12 means "12.x, not 13"; ~2.3 means "2.3 or newer, below 3.0".
Autoloading
With PSR-4, each class lives in its own file whose path matches its namespace. Composer's autoloader then loads classes when they're first used, so you never write require for them:
<?php
declare(strict_types=1);
namespace Asha\Shop;
use Brick\Math\RoundingMode;
use Brick\Money\Money;
use InvalidArgumentException;
final class Cart
{
/** @var array<string, array{price: Money, qty: int}> */
private array $items = [];
public function add(string $sku, Money $price, int $qty = 1): self
{
if ($qty < 1) {
throw new InvalidArgumentException('Quantity must be at least 1');
}
$current = $this->items[$sku]['qty'] ?? 0;
$this->items[$sku] = ['price' => $price, 'qty' => $current + $qty];
return $this;
}
public function count(): int
{
return array_sum(array_column($this->items, 'qty'));
}
public function total(): Money
{
$total = Money::zero('INR');
foreach ($this->items as $item) {
$total = $total->plus($item['price']->multipliedBy($item['qty']));
}
return $total;
}
public function totalWithDiscount(int $percent): Money
{
if ($percent < 0 || $percent > 100) {
throw new InvalidArgumentException('Discount must be 0-100');
}
return $this->total()->multipliedBy(100 - $percent)->dividedBy(100, RoundingMode::HalfUp);
}
}<?php
require __DIR__ . '/../vendor/autoload.php'; // the only require you need
use Asha\Shop\Cart;
use Brick\Money\Money;
$cart = (new Cart())
->add('KB-1', Money::of('49.50', 'INR'))
->add('MS-2', Money::of('19.99', 'INR'), 2);
echo $cart->count(), " items, total ", $cart->total(), "\n";
echo "with 10% off: ", $cart->totalWithDiscount(10), "\n";cd shop
php bin/demo.php3 items, total INR 89.48 with 10% off: INR 80.53
brick/money handles money with exact decimal arithmetic. Floats can't represent amounts like 0.1 exactly, so money libraries (or whole cents) are the professional choice.
Testing with PHPUnit
Tests live in tests/. A test class extends TestCase, and each public method starting with test (or marked #[Test]) is a test:
<?php
declare(strict_types=1);
use Asha\Shop\Cart;
use Brick\Money\Money;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
final class CartTest extends TestCase
{
private Cart $cart;
protected function setUp(): void
{
$this->cart = new Cart(); // a fresh cart before each test
}
public function testEmptyCartTotalsZero(): void
{
$this->assertSame('INR 0.00', (string) $this->cart->total());
$this->assertSame(0, $this->cart->count());
}
public function testAddingTheSameSkuIncreasesQuantity(): void
{
$this->cart->add('KB-1', Money::of(10, 'INR'))->add('KB-1', Money::of(10, 'INR'), 2);
$this->assertSame(3, $this->cart->count());
}
#[DataProvider('discounts')]
public function testDiscount(int $percent, string $expected): void
{
$this->cart->add('KB-1', Money::of(200, 'INR'));
$this->assertSame($expected, (string) $this->cart->totalWithDiscount($percent));
}
public static function discounts(): array
{
return ['none' => [0, 'INR 200.00'], 'ten' => [10, 'INR 180.00'], 'all' => [100, 'INR 0.00']];
}
public function testRejectsZeroQuantity(): void
{
$this->expectException(InvalidArgumentException::class);
$this->cart->add('KB-1', Money::of(10, 'INR'), 0);
}
}cd shop
vendor/bin/phpunit tests --colors=never | sed -E 's/Time: [0-9:.]+, Memory: [0-9.]+ MB/Time: …, Memory: …/; s/^PHPUnit [0-9.]+/PHPUnit 12.x/; s/^Runtime: .*/Runtime: PHP 8.5/'PHPUnit 12.x by Sebastian Bergmann and contributors. Runtime: PHP 8.5 ...... 6 / 6 (100%) Time: …, Memory: … OK (6 tests, 7 assertions)
Each . is a passing test; the data provider turned one test method into three cases. Now let's break the discount on purpose and see a failure:
cd shop
sed -i 's/multipliedBy(100 - $percent)/multipliedBy(100 + $percent)/' src/Cart.php
vendor/bin/phpunit tests --colors=never 2>&1 | sed -n '/^1) /,/^$/p' | head -8
sed -i 's/multipliedBy(100 + $percent)/multipliedBy(100 - $percent)/' src/Cart.php1) CartTest::testDiscount@ten with data (10, 'INR 180.00') Failed asserting that two strings are identical. --- Expected +++ Actual @@ @@ -'INR 180.00' +'INR 220.00'
| Assertion | Checks |
|---|---|
assertSame($expected, $actual) |
Equal value and type (prefer it over assertEquals) |
assertTrue, assertFalse, assertNull |
Booleans and null |
assertCount(3, $list), assertContains($x, $list) |
Arrays |
assertStringContainsString |
Text |
expectException(Foo::class) |
The code that follows throws |
Pest is a popular alternative test framework built on PHPUnit, with shorter syntax: test('discount', fn() => expect($cart->total())->toBe(…));. Laravel projects often use it.
Scripts and quality tools
Add commands to composer.json's scripts so everyone runs them the same way:
cd shop
composer config scripts.test "phpunit tests"
composer config scripts.demo "php bin/demo.php"
composer test 2>&1 | grep -E "^OK"
composer demo 2>&1 | grep -v "^>"OK (6 tests, 7 assertions) 3 items, total INR 89.48 with 10% off: INR 80.53
| Tool | Does |
|---|---|
| PHPStan / Psalm | Static analysis: finds type errors and bugs without running code |
| PHP-CS-Fixer / Laravel Pint | Formats code to the PSR-12 / PER style |
| Rector | Upgrades code automatically to newer PHP versions |
composer audit |
Lists installed packages with known security vulnerabilities |
PSR standards
The PHP-FIG group publishes PSRs (PHP Standards Recommendations) so libraries work together:
| PSR | Defines |
|---|---|
| PSR-4 | Autoloading: namespace ↔ folder |
| PSR-12 / PER | Coding style |
| PSR-3 | Logger interface (Monolog implements it) |
| PSR-7, PSR-15, PSR-17 | HTTP requests, responses and middleware |
| PSR-11 | Dependency-injection containers |
Practice
- Create a project with
composer init, requirenesbot/carbon, and print "3 days from now" in a readable format. - Add a
remove(string $sku)method toCartand write two PHPUnit tests for it. - Turn one test into a data-provider test with four cases.
- Run
composer auditandcomposer outdatedin the project.
1.Which folder should NOT be committed to Git?
2.What does PSR-4 autoloading do?
3.What does composer require --dev phpunit/phpunit mean?
4.Why prefer assertSame over assertEquals?