0
0
PhpHow-ToBeginner · 3 min read

How to Use Composer Require in PHP: Simple Guide

Use composer require vendor/package in your project folder to add a PHP package and update your composer.json automatically. This command downloads the package and its dependencies, making them ready to use in your project.
📐

Syntax

The basic syntax of the composer require command is:

  • composer require vendor/package: Adds the specified package to your project.
  • vendor/package: The name of the package you want to add, usually found on Packagist.
  • Optionally, you can specify a version like vendor/package:^1.2 to require a specific version.
bash
composer require vendor/package
composer require monolog/monolog
composer require guzzlehttp/guzzle:^7.0
💻

Example

This example shows how to add the popular logging library Monolog to your PHP project using composer require. It installs Monolog and updates your composer.json and composer.lock files automatically.

bash
composer require monolog/monolog
Output
Using version ^3.0 for monolog/monolog ./composer.json has been updated Running composer update monolog/monolog Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Installing monolog/monolog (3.0.0): Extracting archive Generating autoload files
⚠️

Common Pitfalls

Some common mistakes when using composer require include:

  • Running the command outside your project folder, so composer.json is not found.
  • Not having Composer installed or not added to your system PATH.
  • Specifying a package name incorrectly or a version that does not exist.
  • Forgetting to include the vendor/autoload.php file in your PHP scripts to load the installed packages.
bash
Wrong:
composer require monolog

Right:
composer require monolog/monolog
📊

Quick Reference

Here is a quick summary of useful tips for composer require:

  • Always run composer require inside your project root where composer.json lives.
  • Use exact package names from Packagist.
  • Specify versions with care, using operators like ^ or ~ for flexibility.
  • After requiring packages, include require 'vendor/autoload.php'; in your PHP files to use them.

Key Takeaways

Run composer require vendor/package inside your project folder to add packages.
Composer updates composer.json and downloads dependencies automatically.
Always use correct package names and optionally specify versions.
Include vendor/autoload.php in your PHP scripts to load installed packages.
Make sure Composer is installed and accessible from your command line.