PHP LogoComposer and Package Management

Composer is an essential dependency manager for PHP. It allows you to declare the libraries your project depends on, and it will install and manage them for you. Beyond just downloading libraries, Composer handles autoloading, making it significantly easier to use third-party code and organize your own project's classes.

Why use Composer?
* Dependency Management: Easily include, update, and remove third-party libraries without manual downloads or complex configuration. Composer automatically resolves dependencies, ensuring compatible versions are installed.
* Autoloading: It generates an autoloader that automatically loads classes from your project's dependencies (e.g., libraries in the `vendor/` directory) and your own project's classes (if configured). This eliminates the need for manual `require` or `include` statements for every class.
* Standardization: Encourages a consistent project structure and development workflow across different projects and developers.
* Version Control: With `composer.lock`, it locks down the exact versions of all installed dependencies, ensuring that every developer and deployment environment uses precisely the same set of libraries, preventing 'it works on my machine' issues.

Key Concepts:
* `composer.json`: This JSON file, located at the root of your project, is the core configuration for Composer. It defines your project's metadata (name, description, authors), and most importantly, its dependencies (`require` section) and how your own classes should be autoloaded (`autoload` section).
* `composer.lock`: Generated after you run `composer install` or `composer update`, this file records the *exact* versions of all direct and indirect dependencies installed. It's crucial for maintaining consistency across environments and should be committed to your version control system.
* `vendor/` Directory: This is where Composer downloads and stores all your project's dependencies. It should generally be excluded from version control (e.g., using `.gitignore`) as it can be regenerated by running `composer install`.
* Autoloading: Composer creates `vendor/autoload.php`. By simply including this file at the start of your application, all classes from your installed packages and your configured local classes become available without manual `require` calls.

Common Composer Commands:
* `composer init`: Interactively creates a new `composer.json` file for your project.
* `composer require vendor/package`: Adds a new package as a dependency to your `composer.json` (e.g., `monolog/monolog`) and installs it into the `vendor/` directory.
* `composer install`: Reads the `composer.json` file and installs all declared dependencies. If `composer.lock` exists, it installs the exact versions specified there, ensuring consistency. If `composer.lock` does not exist, it creates one after resolving and installing dependencies.
* `composer update`: Updates all dependencies to their latest allowed versions based on the constraints in `composer.json`. It then updates `composer.lock` with the new versions.
* `composer dump-autoload`: Regenerates the autoloader files. This is necessary if you manually modify the `autoload` section in `composer.json` or add new classes that need to be autoloaded.

Example Code

To demonstrate Composer, let's create a simple PHP project that uses the Monolog library for logging and also includes some custom application classes managed by Composer's autoloader.

Project Setup Steps:
1.  Create a new directory for your project: `mkdir my_composer_app && cd my_composer_app`
2.  Initialize Composer and require Monolog: `composer require monolog/monolog` (This command will guide you through creating a `composer.json` file and then install Monolog).
3.  After the command, your `composer.json` will look similar to this (you might add an `autoload` section manually):

1. `composer.json`
```json
{
    "name": "your-vendor/my-composer-app",
    "description": "A simple PHP application demonstrating Composer and Monolog.",
    "type": "project",
    "license": "MIT",
    "autoload": {
        "psr-4": {
            "MyApp\\": "src/"
        }
    },
    "require": {
        "php": ">=7.4",
        "monolog/monolog": "^2.0"
    }
}
```

4.  Create the `src` and `var/log` directories:
    `mkdir -p src var/log`

2. `src/LoggerService.php` (Your custom class using Monolog)
```php
<?php

namespace MyApp;

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

class LoggerService
{
    private Logger $logger;

    public function __construct(string $name = 'my_app')
    {
        $this->logger = new Logger($name);
        // Log messages to var/log/app.log
        $this->logger->pushHandler(new StreamHandler(__DIR__ . '/../var/log/app.log', Logger::DEBUG));
    }

    public function logInfo(string $message): void
    {
        $this->logger->info($message);
    }

    public function logError(string $message): void
    {
        $this->logger->error($message);
    }
}
```

3. `public/index.php` (The main application entry point)
```php
<?php

// Include Composer's autoloader. This makes all required libraries
// and our own classes (from src/) available without manual 'require' statements.
require __DIR__ . '/../vendor/autoload.php';

use MyApp\LoggerService;

// Initialize our custom logger service
$loggerService = new LoggerService('WebApp');

$loggerService->logInfo('Application started successfully.');
$loggerService->logInfo('User ' . ($_GET['user'] ?? 'Guest') . ' accessed the homepage.');

try {
    // Simulate an error based on a GET parameter
    if (isset($_GET['error'])) {
        throw new \Exception('A simulated error occurred!');
    }
    echo "<h1>Welcome to My Composer App!</h1>";
    echo "<p>Check the `var/log/app.log` file for details on this request.</p>";
    echo "<p>Try appending `?error=1` to the URL to simulate an error.</p>";
} catch (\Exception $e) {
    $loggerService->logError('An application error occurred: ' . $e->getMessage());
    echo "<h1>An error occurred!</h1>";
    echo "<p>Details have been logged. Please check the `var/log/app.log` file.</p>";
}

echo "<p>Request processing finished.</p>";
```

How to Run:
1.  After setting up the files as described, navigate to `my_composer_app` in your terminal.
2.  Ensure you have run `composer install` (or `composer require monolog/monolog` which runs `install` implicitly).
3.  Start a PHP built-in web server: `php -S localhost:8000 -t public`
4.  Open your web browser and navigate to `http://localhost:8000`.
5.  You will see output in the browser, and detailed logs will be written to `my_composer_app/var/log/app.log`.