PHP Composer – Practical Tutorial
100%

PHP Composer

Composer is a dependency manager for PHP. It helps you install third-party libraries, manage project dependencies, and load PHP classes automatically using autoloading.

Composer is widely used in modern PHP projects, including applications built with Laravel, Symfony, and other PHP frameworks.

1. What Is Composer?

Composer manages the external packages that your PHP application requires.

Main features:

  • Install third-party PHP libraries.
  • Manage project dependencies.
  • Record required packages and version constraints.
  • Generate an autoloader for PHP classes.
  • Help install consistent dependency versions.

For example, if your application needs a PDF generation library, Composer can download and manage that library and its dependencies.

composer require dompdf/dompdf

This command adds Dompdf as a project dependency. Run it from your project directory after installing Composer.

2. Installing Composer

Before using Composer, install PHP and make sure the PHP executable is available from your command line.

On Windows, you can install Composer using its official Windows installer.

Installation steps:

  1. Install PHP, or install a package such as XAMPP that includes PHP.
  2. Download the Composer installer from the official website.
  3. Run the installer and select your PHP executable when prompted.
  4. Open Command Prompt or PowerShell.
  5. Check the installation using the following commands.
php -v
composer --version

The first command displays the installed PHP version. The second displays the Composer version if installation and PATH configuration are correct.

Official website: getcomposer.org

3. Creating a PHP Project

Create a new folder for your project and open a terminal inside that folder.

Example project structure:

composer_demo/
│
├── index.php
├── composer.json
├── composer.lock
└── vendor/

The vendor folder contains installed dependencies and generated autoloading files.

To initialize Composer interactively, run:

composer init

Follow the prompts to create a composer.json file.

You can also create a minimal file manually for a simple project:

{
    "name": "soopro/composer-demo",
    "description": "A simple PHP Composer project",
    "type": "project",
    "require": {}
}

Save this JSON as composer.json in the project root. Composer package names conventionally use a vendor name followed by a package name.

4. Installing Dependencies

Composer uses commands to add packages and install dependencies.

Install dependencies from composer.json
composer install

This installs the dependencies defined by the project. If a compatible composer.lock file exists, Composer uses its recorded versions.

Add a new package
composer require monolog/monolog

This command adds Monolog, a popular logging library, to the project dependencies.

Update dependencies
composer update

This resolves and updates dependencies according to the constraints in composer.json, then updates the lock file.

Be careful with composer update in an existing production application because package versions may change.

5. Understanding composer.json and composer.lock

Composer uses two important files to manage dependencies.

composer.json

This file describes your project and its dependency requirements.

{
    "require": {
        "monolog/monolog": "^3.0"
    }
}
composer.lock

This file records the exact resolved versions of dependencies, including their transitive dependencies.

When your project has a lock file, committing both composer.json and composer.lock to version control helps other developers install the same dependency versions.

After adding or changing dependencies, use composer install in deployment environments to install the versions recorded in the lock file.

6. Using an Installed PHP Library

Once Composer installs a package, load the generated autoloader from your PHP application.

Install the Monolog package:

composer require monolog/monolog

Example: index.php

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('my_app');

$log->pushHandler(
    new StreamHandler(__DIR__ . '/app.log', Logger::WARNING)
);

$log->warning('This is a warning message.');

echo "Log message written successfully.";
?>

If the package is installed successfully, the code creates a logger and writes a warning to app.log.

Make sure the application has permission to write to the directory containing the log file.

7. Composer Autoloading

Autoloading allows PHP classes to be loaded automatically when they are needed, without manually including each class file.

Project structure:

composer_demo/
│
├── composer.json
├── index.php
├── src/
│   └── Student.php
└── vendor/

Step 1: composer.json

{
    "name": "soopro/composer-demo",
    "autoload": {
        "psr-4": {
            "Soopro\\": "src/"
        }
    }
}

This maps the Soopro\ namespace prefix to the src/ directory.

Step 2: src/Student.php

<?php
namespace Soopro;

class Student {
    public function show(): void {
        echo "Student class loaded using Composer.";
    }
}

Step 3: Generate the autoloader

composer dump-autoload

Step 4: index.php

<?php
require_once __DIR__ . '/vendor/autoload.php';

use Soopro\Student;

$student = new Student();
$student->show();
?>

Output:

Student class loaded using Composer.

Composer's PSR-4 autoloader maps the class name to its corresponding file path using the configured namespace prefix.

8. Useful Composer Commands

Here are some commonly used Composer commands.

Command Purpose
composer --version Displays the installed Composer version.
composer init Creates a project configuration interactively.
composer install Installs project dependencies.
composer require vendor/package Adds a package dependency.
composer remove vendor/package Removes a package dependency.
composer update Updates dependencies within their constraints.
composer dump-autoload Regenerates Composer's autoload files.
composer show Displays installed package information.
composer validate Checks the Composer configuration file.

Run Composer commands from your project's root directory, where the composer.json file is located.

9. Practical Example: Composer Project

Let's create a simple project that uses Composer's PSR-4 autoloading to load a student class.

Step 1: Create the project folder
composer_demo/
├── composer.json
├── index.php
├── src/
│   └── Student.php
└── vendor/
Step 2: Create composer.json
{
    "name": "soopro/student-demo",
    "description": "A simple student management example",
    "type": "project",
    "autoload": {
        "psr-4": {
            "Soopro\\Students\\": "src/"
        }
    }
}
Step 3: Create src/Student.php
<?php
namespace Soopro\Students;

class Student {
    private int $id;
    private string $name;
    private string $course;

    public function __construct(
        int $id,
        string $name,
        string $course
    ) {
        $this->id = $id;
        $this->name = $name;
        $this->course = $course;
    }

    public function showDetails(): void {
        echo "Student ID: " . $this->id . "<br>";
        echo "Name: " . $this->name . "<br>";
        echo "Course: " . $this->course;
    }
}
Step 4: Generate the autoloader
composer dump-autoload
Step 5: Create index.php
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Soopro\Students\Student;

$student = new Student(
    101,
    "Rahul Kumar",
    "ADCA"
);

echo "<h2>Student Details</h2>";

$student->showDetails();
?>

Output:

Student Details

Student ID: 101
Name: Rahul Kumar
Course: ADCA

The class is loaded through Composer's generated autoloader. You do not need to manually include src/Student.php in index.php.

Remember that Composer must be installed, and composer dump-autoload must be run after defining or changing the PSR-4 mapping.


🧠 Quick Quiz

1. What is the main purpose of Composer?




2. Which file describes a Composer project's dependencies?




3. Which file is normally loaded to use Composer's generated autoloader?