Introduction
Composer is a dependency management tool used in modern PHP development. It helps developers install external libraries, manage project dependencies, load classes automatically, and maintain compatible package versions. In this chapter, you will practise installing Composer packages, creating project configurations, using autoloading, managing dependencies, and building reusable PHP applications. Packages and Dependency Management in PHP Practice Questions with Solutions to help you to understand the concepts.
Question 1: Check Composer Installation in PHP
Problem Statement
Create a PHP project and check whether Composer is installed on your computer. Composer is required to manage PHP packages and dependencies.
PHP Solution
Open the terminal or command prompt and execute:
composer --version
Sample Output
Composer version 2.x.x
The exact version depends on the Composer installation.
Explanation
composerruns the Composer command-line tool.--versiondisplays the installed Composer in PHP version.- If Composer is installed correctly, the terminal displays its version.
- If the command is not recognized, Composer may not be installed or its executable may not be available through the system PATH.
You can also check the PHP version:
php --version
Composer uses PHP to run its dependency-management operations.
Concepts Covered
- Composer installation
- Command-line interface
- Composer in PHP version
- PHP environment
- Terminal commands
Question 2: Create a New PHP Project Using Composer
Problem Statement
Create a new PHP project using Composer. The project should contain a composer.json file that stores project information and dependency configuration.
PHP Solution
Run the following command in the terminal:
mkdir php-composer-project
cd php-composer-project
composer init
Composer will ask questions about the project.
You can also initialize a project with predefined information:
composer init --name="vsit/php-composer-project" --description="My PHP Composer Project" --type="project" --no-interaction
Sample Output
The project directory will look like this:
php-composer-project/
│
└── composer.json
Example composer.json:
{
"name": "vsit/php-composer-project",
"description": "My PHP Composer Project",
"type": "project"
}
Explanation
mkdircreates a new project directory.cdopens the project directory.composer initcreates a Composer configuration file.--namedefines the package name.--descriptiondescribes the project.--typeidentifies the package type.--no-interactioncreates the configuration without asking questions.
The composer.json file is important because it stores project details, dependencies, and autoloading configuration.
Concepts Covered
- PHP project creation
composer initcomposer.json- Project metadata
- Composer configuration
Question 3: Install a PHP Package Using Composer
Problem Statement
Install the Carbon package in a PHP project. Carbon is a popular PHP library used for working with dates and times.
PHP Solution
First, open your project directory in the terminal and execute:
composer require nesbot/carbon
Composer downloads the package and its required dependencies.
Sample Output
The project directory will look similar to this:
php-composer-project/
│
├── vendor/
│ ├── autoload.php
│ └── nesbot/
│
├── composer.json
└── composer.lock
The composer.json file will contain a dependency similar to:
{
"require": {
"nesbot/carbon": "^3.0"
}
}
The actual version constraint depends on the package version Composer installs.
Explanation
composer requireinstalls a package.nesbot/carbonis the package name.composer.jsonis updated with the dependency.composer.lockrecords the exact installed dependency versions.- The
vendordirectory contains downloaded packages and Composer’s generated files.
You should normally commit both composer.json and composer.lock to your project’s version-control repository. The vendor directory is usually excluded because dependencies can be installed again using Composer.
Concepts Covered
- Composer package installation
composer require- External PHP libraries
- Vendor directory
- Composer lock file
Question 4: Use an Installed Package in PHP
Problem Statement
Use the Carbon package installed in the previous question to display the current date and time in a readable format.
PHP Solution
Create a file named index.php:
<?php
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
$currentDate = Carbon::now();
echo "Current Date: " . $currentDate->format('d-m-Y');
echo "<br>";
echo "Current Time: " . $currentDate->format('h:i A');
?>
Sample Output
Current Date: 17-11-2026
Current Time: 10:30 AM
The displayed time depends on the system timezone and execution time.
Explanation
requireloads Composer’s generated autoloader.vendor/autoload.phpmakes installed package classes available.use Carbon\Carbonimports the Carbon class.Carbon::now()creates an object representing the current date and time.format()displays the date and time in the required format.
You do not need to manually include every Carbon class file. Composer’s autoloader handles class loading.
Concepts Covered
- Using Composer packages
vendor/autoload.php- PHP namespaces
- Carbon library
- Date and time formatting
Question 5: Understand the Difference Between composer.json and composer.lock
Problem Statement
Create a PHP project with a package dependency and understand the difference between composer.json and composer.lock.
PHP Solution
Install a package:
composer require nesbot/carbon
Now examine the following files.
composer.json
{
"require": {
"nesbot/carbon": "^3.0"
}
}
composer.lock
Composer automatically generates this file. It stores the exact versions of the installed packages and their dependency information.
For example, it contains package information similar to:
{
"packages": [
{
"name": "nesbot/carbon",
"version": "3.x.x"
}
]
}
This is only an illustrative extract, not a complete lock file.
Sample Output
composer.json
Stores package requirements and project configuration.
composer.lock
Stores the exact dependency versions selected for installation.
Explanation
Both files have different responsibilities.
| composer.json | composer.lock |
|---|---|
| Defines required packages | Records exact installed versions |
| Contains version constraints | Contains resolved package versions |
| Updated when dependencies are added or changed | Updated when dependency resolution changes |
| Defines project configuration | Helps reproduce the same dependency versions |
For example, ^3.0 allows compatible releases within the Composer version constraint. The lock file records the specific version selected during installation.
Concepts Covered
- Composer configuration
- Dependency version constraints
- Lock file
- Reproducible installations
- Package version management
Question 6: Install Project Dependencies Using composer install
Problem Statement
Create a PHP project that already contains composer.json and composer.lock. Install all required packages using the composer install command.
PHP Solution
Execute the following command inside the project directory:
composer install
If the project contains both composer.json and composer.lock, Composer installs the dependency versions recorded in the lock file, provided they are compatible with the environment.
Sample Output
Installing dependencies from lock file
Package operations: ...
Generating autoload files
Installation completed.
The exact output depends on the number of packages and their versions.
Explanation
composer installinstalls the project’s dependencies.- Composer in PHP reads
composer.jsonto understand the requirements. - If
composer.lockexists, Composer uses the locked versions. - The
vendordirectory is created or updated. - Composer in PHP generates the autoload files.
This command is commonly used when setting up an existing project on another computer or server.
Concepts Covered
composer install- Dependency installation
- Lock file
- Vendor directory
- Project setup
Question 7: Update PHP Packages Using composer update
Problem Statement
Create a PHP project with installed dependencies and update its packages according to the version constraints defined in composer.json.
PHP Solution
Run the following command:
composer update
To update only the Carbon package and its necessary dependencies, execute:
composer update nesbot/carbon
Sample Output
Loading composer repositories with package information
Updating dependencies
Lock file operations: ...
Writing lock file
Generating autoload files
The actual output depends on available package updates and version constraints.
Explanation
composer update checks available package versions and resolves dependencies according to the constraints in composer.json.
- It may install newer compatible versions.
- It updates
composer.lock. - It updates installed packages in the
vendordirectory. - Updating one package can also update related dependencies when required.
Important: composer install and composer update are not the same.
| composer install | composer update |
|---|---|
| Uses locked versions when a lock file exists | Resolves versions again |
| Commonly used to set up an existing project | Commonly used to update dependencies |
| Normally does not change the lock file | Updates the lock file |
Do not run composer update on a production server without testing the resulting dependency changes.
Concepts Covered
composer update- Package updates
- Version constraints
- Dependency resolution
- Lock file management
Question 8: Create PHP Class Autoloading Using Composer PSR-4
Problem Statement
Create a PHP project that automatically loads your own PHP classes using Composer’s PSR-4 autoloading feature.
You will create a Student class inside the src directory and use it without manually including its file.
PHP Solution
Step 1: Create the project structure
php-autoload-project/
│
├── src/
│ └── Student.php
│
├── composer.json
└── index.php
Step 2: Add PSR-4 configuration to composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
Step 3: Create src/Student.php
<?php
namespace App;
class Student
{
public function getName()
{
return "Rahul";
}
}
Step 4: Generate the autoload files
Run:
composer dump-autoload
Step 5: Create index.php
<?php
require __DIR__ . '/vendor/autoload.php';
use App\Student;
$student = new Student();
echo "Student Name: " . $student->getName();
?>
Sample Output
Student Name: Rahul
Explanation
autoloaddefines how Composer should load classes.psr-4configures PSR-4 namespace-based autoloading.App\\is the namespace prefix.src/is the directory containing the class files.namespace App;declares the namespace of theStudentclass.composer dump-autoloadregenerates Composer’s autoload files.vendor/autoload.phploads the configured classes automatically.
Without Composer autoloading, you would need to manually include class files using require or include.
Concepts Covered
- Composer autoloading
- PSR-4 standard
- PHP namespaces
- Class loading
composer dump-autoload
Question 9: Create a Custom PHP Function and Load It Using Composer
Problem Statement
Create a custom PHP function that calculates the total price of a product. Configure Composer to load this function automatically using its files autoload option.
PHP Solution
Step 1: Create the project structure
php-functions-project/
│
├── src/
│ └── functions.php
│
├── composer.json
└── index.php
Step 2: Configure composer.json
{
"autoload": {
"files": [
"src/functions.php"
]
}
}
Step 3: Create src/functions.php
<?php
function calculateTotalPrice($price, $quantity)
{
return $price * $quantity;
}
Step 4: Generate the autoload files
composer dump-autoload
Step 5: Create index.php
<?php
require __DIR__ . '/vendor/autoload.php';
$price = 500;
$quantity = 3;
$total = calculateTotalPrice($price, $quantity);
echo "Product Price: " . $price . "<br>";
echo "Quantity: " . $quantity . "<br>";
echo "Total Price: " . $total;
?>
Sample Output
Product Price: 500
Quantity: 3
Total Price: 1500
Explanation
functions.phpcontains a reusable PHP function.- The
filesoption tells Composer to include the specified file when the autoloader is loaded. composer dump-autoloadregenerates the autoload files.requireloads Composer’s autoloader.- The custom function becomes available without manually including
functions.php.
Use PSR-4 for classes and the files option for functions or files that need to be loaded directly.
Concepts Covered
- Composer files autoloading
- Reusable PHP functions
- Custom project files
- Composer configuration
- Automatic file loading
Question 10: Build a PHP Application Using Composer and an External Package
Problem Statement
Create a small PHP application that uses the Carbon package to calculate a future date.
The application should:
- Install the Carbon package.
- Load the package using Composer.
- Display the current date.
- Calculate a date 30 days in the future.
- Display the calculated date.
PHP Solution
Step 1: Create a project directory
mkdir php-date-project
cd php-date-project
Step 2: Install Carbon
composer require nesbot/carbon
Step 3: Create index.php
<?php
require __DIR__ . '/vendor/autoload.php';
use Carbon\Carbon;
// Get current date
$currentDate = Carbon::now();
// Calculate future date
$futureDate = $currentDate->copy()->addDays(30);
echo "Current Date: ";
echo $currentDate->format('d-m-Y');
echo "<br>";
echo "Date After 30 Days: ";
echo $futureDate->format('d-m-Y');
?>
Sample Output
Current Date: 17-11-2026
Date After 30 Days: 17-12-2026
The output dates depend on the system date and timezone when the program runs.
Explanation
composer requireinstalls the Carbon package.vendor/autoload.phploads the installed package.use Carbon\Carbonimports the Carbon class.Carbon::now()gets the current date and time.copy()creates a separate Carbon object so the original date remains unchanged.addDays(30)adds 30 days to the copied date.format()displays the date in the required format.
This example demonstrates how Composer makes external PHP libraries available in an application without manually downloading and including individual class files.
Concepts Covered
- Composer package installation
- External PHP libraries
- Carbon package
- Autoloading
- Date calculation
- Reusable package functionality
Key Takeaways
- Composer is a dependency management tool for PHP.
composer.jsonstores project configuration and package requirements.composer.lockrecords the exact resolved dependency versions.composer requireinstalls a new package.composer installinstalls dependencies from the lock file when available.composer updateresolves and updates packages according to version constraints.- The
vendordirectory stores installed packages. vendor/autoload.phpautomatically loads configured classes and files.- PSR-4 provides a standard method for namespace-based class autoloading.
composer dump-autoloadregenerates Composer’s autoload files.- Composer in PHP helps developers build reusable and maintainable PHP applications.
Frequently Asked Questions (FAQs)
1. What is Composer in PHP?
Composer is a dependency management tool for PHP. It helps developers install external libraries, manage package versions, and automatically load PHP classes.
2. What is the purpose of composer.json?
composer.json stores project information, package requirements, version constraints, autoloading rules, and other Composer configuration.
3. What is the difference between composer.json and composer.lock?
composer.json defines which packages and versions a project requires. composer.lock records the exact package versions selected during dependency resolution.
4. What is the vendor directory in PHP?
The vendor directory contains packages installed through Composer, along with generated autoload files.
5. What does composer require do?
The PHP composer require command adds a package to the project, updates composer.json, resolves dependencies, and installs the package.
6. What is the difference between composer install and composer update?
composer install uses the versions recorded in composer.lock when the file exists. composer update resolves package versions again according to the constraints in composer.json and updates the lock file.
7. What is autoloading in PHP?
Autoloading automatically loads a PHP class when the application needs it. PHP Composer provides an autoloader so developers do not need to manually include every class file.
8. What is PSR-4 autoloading?
PSR-4 is a PHP standard that maps namespace prefixes to directories. PHP Composer supports PSR-4 to automatically load class files based on their namespaces.
9. What does composer dump-autoload do?
composer dump-autoload regenerates Composer’s autoload files using the current autoload configuration. It is useful after changing PSR-4 mappings or files autoloading rules.
10. Should the vendor directory be uploaded to GitHub?
Usually, the vendor directory is excluded from Git repositories because dependencies can be installed again using composer install. However, composer.json and composer.lock should normally be committed.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
