Composer helps you add and manage libraries your PHP project needs easily. It keeps track of these libraries and their versions so your project works smoothly.
0
0
Composer require and dependency management in PHP
Introduction
When you want to add a new library to your PHP project without downloading files manually.
When you need to update libraries to their latest versions safely.
When you want to share your project and ensure others get the same libraries automatically.
When you want to avoid conflicts between different library versions in your project.
Syntax
PHP
composer require vendor/package # Example: composer require monolog/monolog
composer require adds a library to your project and updates composer.json automatically.
You run this command in your project folder using a terminal or command prompt.
Examples
Adds the Monolog library to your project for logging.
PHP
composer require monolog/monolog
Adds Guzzle HTTP client version 7.0 or higher but less than 8.0.
PHP
composer require guzzlehttp/guzzle:^7.0Adds PHPUnit only for development (testing) purposes.
PHP
composer require --dev phpunit/phpunit
Sample Program
This PHP script uses Monolog, a library added by composer require monolog/monolog. It creates a log file and writes warning and error messages.
PHP
<?php require 'vendor/autoload.php'; use Monolog\Logger; use Monolog\Handler\StreamHandler; // Create a log channel $log = new Logger('name'); $log->pushHandler(new StreamHandler('app.log', Logger::WARNING)); // Add records to the log $log->warning('This is a warning'); $log->error('This is an error'); echo "Logs have been written to app.log\n";
OutputSuccess
Important Notes
Always run composer install after cloning a project to get all dependencies.
Use composer update carefully as it updates all libraries to latest allowed versions.
Check composer.json and composer.lock files to see your project's dependencies and exact versions.
Summary
Composer require adds libraries and manages them automatically.
It updates composer.json and downloads the needed files.
Use it to keep your PHP project organized and up to date.