← Вернуться к курсу: PHP from scratch

Namespaces, Composer and week 6 review

Видео скоро появится

With many classes in many files two problems appear: names can clash (two libraries with a Logger class) and loading every file with require_once becomes tedious. Namespaces solve the first and Composer, the PHP dependency manager, the second. Composer also installs third-party libraries with one command. Today it is essential in any professional PHP project, so we will devote this lesson to getting your project ready with a standard structure.

Namespaces

A namespace is like a folder for class names. It is declared at the top of the file, after declare(strict_types=1), with namespace App\Domain;. The full class name becomes App\Domain\Product. To use it from another namespace you write the full name or, better, import it with use at the top of the file. With use ... as you can give an alias if two classes share the same short name. By convention, the namespace mirrors the folder structure, and each file contains a single class with the same name as the file.

php
<?php
// File: src/Domain/Product.php
declare(strict_types=1);

namespace App\Domain;

final class Product
{
    public function __construct(
        public readonly string $name,
        public readonly float $price,
    ) {
    }

    public function label(): string
    {
        return sprintf('%s - %.2f', $this->name, $this->price);
    }
}

Composer and PSR-4 autoload

Composer is installed from getcomposer.org and used in the terminal. With composer init you create the composer.json file, which describes your project and its dependencies. The autoload section with PSR-4 tells Composer that the App\ namespace lives in the src/ folder. After running composer dump-autoload, Composer generates vendor/autoload.php: by including it once, each class loads itself the first time you use it. You will no longer write require_once for your classes. The vendor folder is not committed to Git; it is regenerated with composer install.

php
{
    "name": "demo/shop",
    "description": "Small PHP demo shop",
    "type": "project",
    "require": {
        "php": ">=8.3"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
php
<?php
// File: public/index.php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use App\Domain\Product;

$product = new Product('Coffee', 3.5);
echo $product->label(), "\n"; // Coffee - 3.50

To install a third-party library you use composer require vendor/package; for example, composer require vlucas/phpdotenv to read environment variables from a .env file. Composer downloads the package into vendor, records the version in composer.json and registers the exact versions in composer.lock, which you must commit to Git so the whole team uses the same ones. Before adding a dependency ask yourself whether you really need it, whether it is maintained and who it comes from: each package is someone else's code running on your server.

Проверьте себя

Вопрос 1 из 6

Which file do you include once to load your classes with Composer?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →