JINSI YA KUTUMIA COMPOSER KWA DEPENDENCY MANAGEMENT KATIKA PHP
Inaruhusu install na update libraries automatically
Manages package versions ili project iwe stable
Simplifies autoloading na reduces manual inclusion
Goal: Make PHP projects modular, maintainable, and scalable.
⚙️ 2. Installing Composer
Download Composer from: https://getcomposer.org/download/
Verify installation:
composer --version
Expected output: Composer version x.x.x ...
🧩 3. Creating composer.json
Navigate to project root and run:
composer init
Follow prompts: project name, description, author, minimum stability, etc.
Generates a composer.json file.
Example composer.json:
{
"name": "faustine/mvc-project",
"description": "Sample PHP project using MVC and Composer",
"require": {
"monolog/monolog": "^3.0"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
}
}
🧩 4. Installing Dependencies
composer install
Creates vendor/ folder
Generates vendor/autoload.php for autoloading packages
To update dependencies:
composer update
🧩 5. Using Installed Packages
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
// Create a log channel
$log = new Logger('app');
$log->pushHandler(new StreamHandler(__DIR__.'/app.log', Logger::DEBUG));
// Add records
$log->info('This is an info message.');
$log->error('This is an error message.');
💡 Maelezo:
Composer handles autoloading automatically
No need to manually include class files
Ensures version compatibility and reproducibility
🔑 6. Best Practices
Commit composer.json and composer.lock, not vendor/.
Use PSR-4 autoloading for project classes.
Avoid manually including external libraries.
Run composer update carefully – check for breaking changes.
Use semantic versioning for package stability.
✅ 7. Hitimisho
Composer simplifies PHP dependency management and autoloading.
Makes projects maintainable, modular, and scalable.
Essential for modern PHP development with libraries, frameworks, and tools.
🔗 Tembelea:
👉 https://www.faulink.com/
Kwa mafunzo zaidi ya PHP, Composer usage, na best practices za project management.