Dorokhov.codes

Composer

Composer is a tool for dependency management in PHP. It allows us to declare the libraries our project depends on, and it will manage them for us.

There are two main files we will deal with:

composer.json
composer.lock

composer.json is a file where we specify the libraries our project depends on. We work only with this file. We can create this file manually.

composer.lock is a file which is generated automatically using update command. update command looks through the composer.json and pick up the latest versions of the packages and store this information to the composer.lock file.

To install all the packages which are specified in the composer.lock file, we use the install command.

composer.json

For example, to add a new dependency, we can use the next composer.json:

{
  "require" : {
    "steadfast/telegram-bot-api": "2.3.0"
  }
}

And run composer update.

Setting up a library version

The next formats are allowed:

  • 1.0.2 - specific version.
  • >=1.0.0 - version range.
  • >=1.0.0 <2.0 - version range.
  • 1.0.0-1.0.9 - version range.
  • 1.0.* - the last revision version.
  • dev-master - choosing a master branch in a repository.
  • ~1.2 - the ~ operator is best explained by example: ~1.2 is equivalent to >=1.2 <2.0.0, while ~1.2.3 is equivalent to >=1.2.3 <1.3.0.

Library packages

This is a default approach.

Application packages

Besides the fact that we can create libraries, we can also create applications packages. It can be a ready-made application that you can use without having to do anything.

Composer has a special command for such projects - create-project. This is the equivalent of doing a git clone.

To create a new project using Composer you can use the create-project command. Pass it a package name, and the directory to create the project in. You can also provide a version as third argument, otherwise the latest version is used:

composer create-project "steadfast/telegram-bot-api" . "2.3.0"

Including a local library

For example, you don’t want to upload your library to the Packagist, but you want to use it in your projects. How to act it this situation?

The solution is very simple. We need to create a local repository (just a folder with your libraries). And then we are including it like this:

{
    "repositories": [
        {
            "type": "path",
            "url": "../../path/to/repository"
        }
    ],
    "require": {
        "author/package": "*"
    }
}

We need to specify a path (url) to the folder, that contains composer.json of the target library. Composer relies on a name in the composer.json, and not on the folder structure or names.

Docs.

Using a private library on GitHub

{
    "repositories": [
        {
            "type": "vcs",
            "url": "git@github.com:your-github-username/your-repository-name.git"
        }
    ]
}