How to start using composer.phar

Ingmar Aasoja
RSS: Share:

This blog post is more than 14 months old and may be out of date.

Until recently, there was no one uniform way to install libraries for PHP. The solutions varied depending on the framework. This changed with the appearance of Composer dependency manager, that has now become the standard tool for adding dependencies for an application or even for managing framework components. Composer is an easy-to-use tool for installing both freeware and in-house packages and setting up projects.

Note! This blog article is first of all aimed at beginner PHP developers who have already tried some common frameworks, such as Laravel or Symfony, and want to experiment with building something from scratch.

How to start using composer.phar

In short, Composer is a package manager, but it actually does much more. Composer is already installed on all servers on our Zone platform, and you can use it on your virtual server without having to do any extra work. Composer solves a number of problems that would otherwise create extra work for developers. The two most important of these problems are the following:

1. Dependency and library management

If you wish to use a third-party library, you can add it with just one command in Composer. The library in question must already be included in the Composer repository. The repository can be both public and in-house, used for private code.

Installing libraries is easy with Composer as you can do it with just one statement. During installation, Composer checks the compatibility of your libraries. This is particularly useful in situations where the compatibility of one library version differs from that of another library, and both libraries depend on a third package. Composer will find the newest possible compatible and concurrent version. If this is not possible, Composer will notify you.

2. Autoloading classes

Those little more knowledgeable in history should be aware of the time before the class autoloading standards were introduced. Back then, each application had its own code to look up files containing classes and not yet loaded in the PHP code. In some cases, all classes that might be used by the code were loaded at the beginning of code execution by merging all files with the “require_once” statement.

Fortunately, the PSR-0 standard and after that the more modern PSR-4 were created in the course of time, defining how the class name should correspond to the file tree hierarchy. Nowadays, you don’t have to get into this too deeply, because Composer helps you to set up autoloaders for all classes, and the person writing the PHP code can concentrate on their job.

Simple Composer usage example

No matter how simple your application or script, it is always easy to start by setting up Composer if planning to use external libraries.

In order to demonstrate Composer’s minimum level capabilities and show you how easy it makes your life, we will create a CLI (terminal executable) application that will use HTTP to check some URL and its HTTP code. Although you can do this easily with Curl, we will use a separate package called Guzzle for this sample code.

First, we will create a directory called pinger and enter this directory:

mkdir pinger
cd pinger

We will write our PHP code to a file called pinger.php. Let’s assume all classes we have written ourselves are located in the src directory and have been created according to the PSR-4 standard.

Let’s start the project by executing the following statement:

composer init

You will be prompted to answer a number of questions after that. Most of them are optional, but it is still worth setting up some of the more important ones.

  • Package name is the freely chosen name for the application created, using the package-creator/package-name format.
  • Description is a short description for the application or library.
  • Author defines the author. This is useful if intending to make the software you have created publicly available.
  • The Minimum Stability determines the minimum stability requirement for libraries added via Composer. When creating an application, striking the balance between stability and newness of the versions is often important. This can be set with the values dev or stable, which are self-describing.
  • Package Type describes the type of software you are going to create. For example, “package” is suitable for a library to be used as part of another application, and “project” for a standalone application to which libraries are added.
  • The License field must be filled in if the code is going to be publicly available. Otherwise, it doesn’t matter very much.

Next, you will be asked if you wish to install any dependencies at this point. We will skip this part for the time being by simply pressing Enter.

When the Add PSR-4 autoload mapping? prompt is displayed, we will create the PSR-4 autoload settings that are derived from the very first question. This means the PascalCase version of our package name will divide the vendor and package names between namespaces. For our sample code, we will configure MyPackage to do this.

Next, we only need to confirm the created composer.json by pressing Enter.

Composer created the following files and directories based on its default settings:

  • the src directory containing the code located in the application’s namespace,
  • the vendors directory for installing the dependencies, i.e. libraries to be installed via the Composer. This directory also contains the autoload.php file to be included in the PHP script.
  • the composer.json file with Composer settings for this project.

Now that composer.json has been created, we need to deploy its autoloader that will take care of autoloading both the application itself and the classes of the libraries added. To do this, we will create a PHP file called pinger.php for the application, to be used in CLI.

<?php

use Composer\Autoload\ClassLoader;

// laeme sisse composer'i
require_once __DIR__ . '/vendor/autoload.php';

Code language: PHP (php)

We will now install the Guzzle 7 HTTP client application. To do this, we will execute the following command:

composer require guzzlehttp/guzzle:^7.0Code language: JavaScript (javascript)

A file called composer.lock was created in our root directory. This file will store the exact version of the currently installed dependencies. When executing the composer install command next time, the libraries will be installed using exactly the same version, ensuring the same minor and patch versions will be used as at the time of creating or updating the application.

Let us modify the pinger.php file to use the Guzzle library to display the HTTP response code for some URLs.

<?php

use GuzzleHttp\Client;

require_once __DIR__ . '/vendor/autoload.php';

$siteUrl = 'https://www.google.com';

$client = new GuzzleHttp\Client(['base_uri' => $siteUrl]);
$response = $client->request('GET', '');

echo $response->getStatusCode();
Code language: HTML, XML (xml)

This script will output the HTTP code of the corresponding URL, meaning a successful request for 2XX.

When creating a web application, the docroot used for directing Apache HTTP requests should be located in a separate directory, e.g. public. This directory should contain the so-called front controller index.php that will receive all requests and execute the code based on this using the classes located in the src directory.

Let’s create the file public/index.php.

<?php

use MyPackage\Controller;

require_once __DIR__ . '/../vendor/autoload.php';

(new Controller())->showPage();Code language: HTML, XML (xml)

Let’s create the class file src/Controller.php for the controller. As we have previously set up the PSR-4 autoloader for the corresponding namespace, the corresponding class is loaded in index.php without having to specify a separate file.

<?php

namespace MyPackage;

use GuzzleHttp\Client;

class Controller
{
    public function showPage()
    {
        $siteUrl = 'https://www.google.com';

        $client = new Client(['base_uri' => $siteUrl]);
        $response = $client->request('GET', '');

        echo $response->getStatusCode();
    }
}Code language: HTML, XML (xml)

When we now point the docroot variable to the public directory, the browser will display the HTTP code, similarly to the command line application.

Note! As a general rule, you must not assign a directory containing files added with Composer or the application’s class files as docroot. That’s why we created a separate public directory here, and the entire code is located in the directory tree above it, so that it cannot be accessed over HTTP.

In conclusion

The solution created provides a simple way for starting to create a PHP application from scratch using Composer. While it is not always a good idea to reinvent the wheel, it sometimes makes sense to write an application without a framework in order to learn the language or create very simple applications. This post is meant to be just a guide, and the sample code described here does not really perform any complicated actions 🙂

Popular posts

Zone Webmail 3.0: New features that make email management easier than ever

Zone Webmail 3.0: New features that make email management easier than ever

Nikita Tikhomirov
The upgraded version of Zone Webmail is here, offering a fresh and user-friendly experience. Our goal with this new update was simple: every feature should...
Still the rightful owner of your domain? ICANN’s new rule means it’s time to double-check

Still the rightful owner of your domain? ICANN’s new rule means it’s time to double-check

Jaanus Putting
Starting 28 May 2025, a new policy by ICANN comes into effect, and it impacts all owners of generic domains like .COM, .ORG, and .NET. Sounds technical?...
Why choose a .EU domain today?

Why choose a .EU domain today?

Jaanus Putting
We live in a time where global power dynamics are shifting faster than ever before. While Europe is moving towards a stronger, more unified internal market,...
Ecommerce SEO essentials: How to boost search visibility and drive sales

Ecommerce SEO essentials: How to boost search visibility and drive sales

Montonio
When someone Googles phrases like “best budget trail shoes” or “ceramic non-stick skillet,” they’re not browsing casually — they’re ready...