Using Composer: PHP Package Management Explained πŸš€

Using Composer: PHP Package Management Explained πŸš€

Composer is the go-to dependency manager for PHP. If you’re still copy-pasting libraries manually, it’s time to level up your workflow! πŸ’ͺ

🎯 In this guide, you’ll learn:

βœ… What Composer is and why you should use it
βœ… How to install and configure Composer
βœ… How to install and autoload PHP packages
βœ… How to create your own Composer package
βœ… A real-world mini project using Composer

Let’s dive in! πŸš€


1️⃣ What is Composer?

πŸ’‘ Composer is a dependency manager for PHP that automatically installs, updates, and loads packages (libraries) for your project.

πŸ”₯ Why use Composer?
βœ… Manages dependencies easily
βœ… Prevents compatibility issues
βœ… Autoloads classes (No more require headaches!)
βœ… Speeds up development


2️⃣ Installing Composer

βœ… Installation on Windows

1️⃣ Download the Composer installer from getcomposer.org.
2️⃣ Run the installer and follow the instructions.
3️⃣ Open Command Prompt and verify installation:

composer -V

βœ… Installation on macOS/Linux

Run the following command in the terminal:

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

Verify installation:

composer -V

You should see something like:

Composer version 2.x.x

3️⃣ Creating a New PHP Project with Composer

Let’s create a new project and manage dependencies using Composer.

1️⃣ Initialize a New Composer Project

Navigate to your project directory and run:

composer init

It will ask for details like:

  • Package name (zeroexp/dev-project)
  • Description (My first PHP project with Composer)
  • Author (Zero Dev <zero@zeroexp.dev>)
  • Minimum stability (stable)

At the end, Composer generates a composer.json file.


4️⃣ Installing PHP Packages with Composer

πŸ’‘ Let’s install some useful packages using Composer!

Example 1: Installing a Logger (monolog/monolog)

composer require monolog/monolog

πŸ”₯ What happens?
βœ… Downloads the monolog/monolog package from Packagist.
βœ… Adds it to composer.json.
βœ… Creates a vendor/ folder with all dependencies.

Using the Installed Package in PHP

<?php
require "vendor/autoload.php"; // Automatically loads installed packages

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

$log = new Logger("app");
$log->pushHandler(new StreamHandler("app.log", Logger::WARNING));

$log->warning("This is a warning!");
$log->error("This is an error!");
?>

πŸ”₯ Why use vendor/autoload.php?
βœ… Automatically loads all installed packages without requiring files manually.


5️⃣ Updating and Removing Packages

Update Packages to Latest Version

composer update

Remove a Package

composer remove monolog/monolog

πŸ”₯ What happens?
βœ… Removes the package from composer.json and vendor/.


6️⃣ Using Composer Autoload for Your Own Classes

πŸ’‘ You can also autoload your own PHP classes!

1️⃣ Create a Folder for Your Code

mkdir src

2️⃣ Create a Sample Class in src/Utils/Helper.php

<?php
namespace App\Utils;

class Helper {
    public static function greet($name) {
        return "Hello, $name!";
    }
}
?>

3️⃣ Configure Autoloading in composer.json

"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
}

4️⃣ Run the Composer Dump-Autoload Command

composer dump-autoload

πŸ”₯ What happens?
βœ… Generates vendor/autoload.php to automatically load classes.

5️⃣ Use Your Custom Class in index.php

<?php
require "vendor/autoload.php";

use App\Utils\Helper;

echo Helper::greet("Zero Dev");
?>

πŸ”₯ Boom! No more require statements! πŸŽ‰


7️⃣ Creating Your Own Composer Package

Want to share your code with the world? Create a public Composer package!

Step 1: Create a Package Directory

mkdir my-package && cd my-package
composer init

Step 2: Add Your Code (src/Calculator.php)

<?php
namespace MyPackage;

class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }
}
?>

Step 3: Configure Autoloading in composer.json

"autoload": {
    "psr-4": {
        "MyPackage\\": "src/"
    }
}

Step 4: Run composer dump-autoload

composer dump-autoload

Step 5: Test Your Package

<?php
require "vendor/autoload.php";

use MyPackage\Calculator;

$calc = new Calculator();
echo $calc->add(5, 10); // Output: 15
?>

πŸ”₯ Now your package is ready for Packagist! πŸš€


8️⃣ Publishing Your Package to Packagist

πŸ’‘ Want to make your package public?

1️⃣ Push your code to GitHub

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-package.git
git push -u origin main

2️⃣ Submit your package to Packagist

  • Go to packagist.org
  • Submit your GitHub repository link
  • Run composer require yourname/my-package to install it! πŸŽ‰

🎯 Mini Project: Build a JSON API with Composer Packages

Let’s build a simple JSON API using Composer.

1️⃣ Install Dependencies

composer require slim/slim "^4.0"
composer require monolog/monolog

2️⃣ Create index.php

<?php
require "vendor/autoload.php";

use Slim\Factory\AppFactory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$app = AppFactory::create();

$log = new Logger("api");
$log->pushHandler(new StreamHandler("api.log", Logger::INFO));

$app->get('/hello/{name}', function ($request, $response, $args) use ($log) {
    $log->info("Saying hello to " . $args['name']);
    $response->getBody()->write(json_encode(["message" => "Hello, " . $args['name']]));
    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();
?>

3️⃣ Start the API Server

php -S localhost:8000

4️⃣ Test the API

Visit:

http://localhost:8000/hello/ZeroDev

πŸ’₯ You just built an API using Composer! πŸŽ‰


πŸš€ Final Thoughts

Now you’re a Composer pro!
βœ… Install and manage PHP packages
βœ… Use Composer for autoloading
βœ… Create and publish your own packages
βœ… Build real-world projects with Composer

πŸ‘‰ Next: PHP and APIs

Happy coding! πŸŽ‰πŸš€

Leave a Reply