Best PHP Composer Installation Guide on Debian 12 Bookworm
In this guide, we aim to provide a comprehensive PHP Composer Installation Guide on Debian 12 Bookworm. As you likely know, Composer is an essential dependency management tool for PHP projects. It simplifies the process of installing, updating, and managing the various libraries and packages your project relies on.
This tutorial, brought to you by Orcacore, will guide you through installing Composer on Debian 12 and demonstrate its usage step-by-step. By the end of this article, you’ll have a solid understanding of how to leverage Composer to streamline your PHP development workflow.
Before diving into this PHP Composer Installation Guide on Debian 12 Bookworm, ensure you have access to your Debian 12 server as a non-root user with sudo privileges. A basic firewall setup is also recommended. If you haven’t already done so, refer to this guide on Initial Server Setup with Debian 12 Bookworm for detailed instructions.
Once you’ve completed the prerequisites, proceed with the following steps to successfully complete the PHP Composer Installation Guide on Debian 12 Bookworm.
Step 1 – Install Required Packages for Composer
First, update your system’s package list with the following command:
sudo apt update
Next, install the necessary packages for Composer to function correctly:
sudo apt install php-cli unzip curl -y
This command installs php-cli
(the PHP command-line interpreter), unzip
(for extracting zipped archives), and curl
(a command-line tool for transferring data with URLs). The -y
flag automatically confirms the installation of the packages.
Step 2 – Download Composer Installer on Debian 12
In this PHP Composer Installation Guide on Debian 12 Bookworm, we’ll utilize the Composer installer script, written in PHP, to install Composer itself. Download the installer script using the following curl command:
# cd ~
# sudo curl -sS https://getcomposer.org/installer -o composer-setup.php
This command downloads the installer script from https://getcomposer.org/installer
and saves it as composer-setup.php
in your home directory. The -sS
flags ensure that the download is silent (suppresses progress output) and shows errors if they occur.
Step 3 – Install PHP Composer on Debian 12 Bookworm
Now that you have the installer script, you can proceed with the installation of Composer globally. Run the following command:
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer
This command executes the composer-setup.php
script using the PHP interpreter. The --install-dir=/usr/local/bin
option specifies the directory where Composer will be installed (in this case, /usr/local/bin
, which is a standard location for executable files). The --filename=composer
option sets the name of the Composer executable to composer
.
Upon successful execution, you should see output similar to the following:
**Output**
All settings correct for using Composer
Downloading...
Composer (version 2.6.2) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
To verify the PHP Composer Installation Guide on Debian 12 Bookworm, you can run the following command:
composer
This should produce output similar to the following:
**Output**
______
/ ____/___ ____ ___ ____ ____ ________ _____
/ / / __ / __ `__ / __ / __ / ___/ _ / ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
____/____/_/ /_/ /_/ .___/____/____/___/_/
/_/
Composer version 2.6.2 2023-09-03 14:09:15
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--profile Display timing and memory usage information
--no-plugins Whether to disable plugins.
--no-scripts Skips the execution of all scripts defined in composer.json file.
-d, --working-dir=WORKING-DIR If specified, use the given directory as working directory.
--no-cache Prevent use of the cache
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
about Shows a short information about Composer
archive Creates an archive of this composer package
audit Checks for security vulnerability advisories for installed packages
browse [home] Opens the package's repository URL or homepage in your browser
...
This confirms that Composer has been successfully installed and is accessible system-wide.
Step 4 – How To Use Composer on Debian 12?
To utilize Composer within your projects, you’ll need a composer.json
file. This file acts as a manifest, declaring the dependencies required by your project. While you can manually create this file, Composer provides an interactive mode that guides you through the process based on your input.
In this step of the PHP Composer Installation Guide on Debian 12 Bookworm, we’ll demonstrate how to use Composer with the PHP package repository called Packagist.
Create a Test Project with Composer
First, visit the Packagist official site and search for the desired Composer repository. For this example, we’ll search for "Slugify," a package that converts strings into URL-friendly slugs.
The cocur/slugify
package is a popular choice for this purpose.
Next, create a Composer project directory on Debian 12 Bookworm and navigate to it using the following commands:
# cd ~
# mkdir slugify
# cd slugify
Now, use the composer require
command, specifying the repository package you want to install. This command also automatically creates the composer.json
file:
composer require cocur/slugify

As you can see from the output, Composer automatically determines the appropriate version of the package to use. To examine the files in your project directory, use the following command:
ls -l
**Output**
total 12
-rw-r--r-- 1 root root 59 Sep 13 05:56 composer.json
-rw-r--r-- 1 root root 3114 Sep 13 05:56 composer.lock
drwxr-xr-x 4 root root 4096 Sep 13 05:56 vendor
You’ll notice three items: the composer.json
file, the composer.lock
file, and a vendor
directory.
The lock file stores information about the specific versions of each installed package. The vendor directory houses the project’s dependencies.
Automatically Load Dependencies with Composer
Composer provides an autoload script that simplifies the process of including dependencies in your project. This script is automatically generated when you add your first dependency.
To enable autoloading, simply include the vendor/autoload.php
file in your PHP scripts before instantiating any classes from the installed packages.
Create a new file named test.php
using your preferred text editor (e.g., vi):
vi test.php
Add the following code to the file:
<?php
require __DIR__ . '/vendor/autoload.php';
use CocurSlugifySlugify;
$slugify = new Slugify();
echo $slugify->slugify('Hello World, this is a long sentence and I need to make a slug from it!');
Save and close the file.
Run the script using the following command:
php test.php
The output will be:
**Output**
hello-world-this-is-a-long-sentence-and-i-need-to-make-a-slug-from-it
Update Composer Dependencies
To update your project’s dependencies to more recent versions, use the composer update
command:
composer update
If a newer version of a package is available and compatible with the version constraints defined in your composer.json
file, Composer will update the installed version.
You can also update specific libraries using the following command:
composer update vendor/package vendor2/package2
Note: After updating your dependencies, be sure to commit the changes to both the composer.json
and composer.lock
files to your version control system. This ensures that other developers working on the project will use the same versions of the dependencies.
Conclusion
You have now successfully completed the PHP Composer Installation Guide on Debian 12 Bookworm step-by-step and learned how to use it by creating a sample project.
Hopefully, you found this guide helpful. You might also be interested in these related articles:
Install Symfony PHP Framework on Debian 12
Install and Secure phpMyAdmin on Debian 12
Alternative Solutions for Dependency Management
While Composer is the industry-standard dependency manager for PHP, alternative approaches and tools exist for managing project dependencies. Here are two different ways to solve the problem of dependency management in PHP, along with explanations and code examples:
1. Using Phar Archives and Autoloading:
This method involves downloading pre-built .phar
(PHP Archive) files for each dependency and manually including them in your project, along with setting up a custom autoloader. While less automated than Composer, it can be suitable for smaller projects with fewer dependencies.
-
Explanation: Phar archives are essentially self-contained PHP applications or libraries packaged into a single file. They can be executed directly by the PHP interpreter. To use a Phar archive as a dependency, you download it, include it in your project, and then use a custom autoloader to load the classes within the archive.
-
Code Example:
First, download the Phar archive of your desired library (e.g., a simple string manipulation library). Let’s assume you’ve downloaded
string-utils.phar
.<?php // Autoloader function spl_autoload_register(function ($class) { $pharPath = 'phar://' . __DIR__ . '/string-utils.phar/' . str_replace('\', '/', $class) . '.php'; if (file_exists($pharPath)) { require $pharPath; } }); // Example Usage (assuming the library has a namespace 'StringUtils') use StringUtilsStringHelper; $helper = new StringHelper(); echo $helper->uppercase('hello world'); // Output: HELLO WORLD ?>
Explanation of the Code:
spl_autoload_register()
: Registers a custom autoloader function.$pharPath
: Constructs the path to the PHP file within the Phar archive based on the class name. It assumes a directory structure within the Phar that mirrors the namespace.file_exists()
: Checks if the file exists within the Phar archive.require $pharPath
: Includes the PHP file, loading the class definition.use StringUtilsStringHelper
: Imports theStringHelper
class from theStringUtils
namespace.- The rest of the code demonstrates how to use the loaded class.
This approach requires you to create and maintain the autoloader manually and update the Phar archives yourself.
2. Using a Simple Dependency Management Script (DIY):
For very simple projects, you could create a basic PHP script that downloads dependencies from specified URLs and places them in a designated directory. This approach lacks the features and robustness of Composer but can be useful in highly constrained environments.
-
Explanation: This method involves creating a PHP script that reads a configuration file (e.g.,
dependencies.json
) containing a list of dependencies and their download URLs. The script then usescurl
orfile_get_contents
to download the files and save them to a directory. You would then need to manually include these files or set up an autoloader. -
Code Example:
Create a
dependencies.json
file:{ "dependencies": [ { "name": "Monolog", "url": "https://github.com/Seldaek/monolog/releases/download/2.9.2/monolog-2.9.2.zip", "extract_to": "vendor/monolog" } ] }
Create a
install_dependencies.php
file:<?php $dependenciesFile = 'dependencies.json'; $dependencies = json_decode(file_get_contents($dependenciesFile), true); if ($dependencies === null || !isset($dependencies['dependencies'])) { die("Error: Invalid dependencies.json file.n"); } foreach ($dependencies['dependencies'] as $dependency) { $name = $dependency['name']; $url = $dependency['url']; $extractTo = $dependency['extract_to']; echo "Downloading $name from $url...n"; // Download the file $tempFile = tempnam(sys_get_temp_dir(), 'dependency_'); $file = fopen($url, 'rb'); if ($file) { $newFile = fopen($tempFile, 'wb'); if ($newFile) { while (!feof($file)) { fwrite($newFile, fread($file, 1024 * 8)); } } fclose($newFile); fclose($file); } else { die("Error: Failed to download $name from $url.n"); } // Extract the file (assuming it's a zip file) if (strpos($url, '.zip') !== false) { echo "Extracting $name to $extractTo...n"; $zip = new ZipArchive; if ($zip->open($tempFile) === TRUE) { if (!is_dir($extractTo)) { mkdir($extractTo, 0777, true); // Create directories recursively } $zip->extractTo($extractTo); $zip->close(); } else { die("Error: Failed to extract $name.n"); } } else { die("Error: Only zip files are supported for extraction.n"); } unlink($tempFile); echo "Installed $name successfully!n"; } echo "All dependencies installed!n"; ?>
Explanation of the Code:
- The script reads the
dependencies.json
file. - It iterates through each dependency.
- It downloads the dependency file using
fopen
,fwrite
, andfread
. - It extracts the downloaded ZIP file to the specified directory using
ZipArchive
. This assumes all dependencies are provided as ZIP files. - It handles basic error checking.
To use the installed dependencies, you would need to include the necessary files or create an autoloader.
This approach is very basic and lacks features like version management, conflict resolution, and dependency resolution. It is suitable only for the simplest of projects where Composer is not an option.
- The script reads the
Conclusion:
While Composer remains the recommended solution for PHP dependency management due to its comprehensive feature set and wide adoption, these alternative approaches can be considered in specific scenarios where Composer is not feasible or necessary. Remember to carefully evaluate the trade-offs before choosing an alternative method. This PHP Composer Installation Guide on Debian 12 Bookworm recommends using composer, as it provides the best features for dependency management.