Composer tips

Nikola Poša

Web developer & Open-Source Contributor

Workflow

  • Initial installation of project dependencies:
    composer install
  • Sync with someone else's changes:
    composer install
  • Add new dependency:
    composer require vendor/package
  • Update specific dependency:
    composer update vendor/package
  • Update all project dependencies:
    composer update
  • Remove specific dependency:
    composer remove vendor/package

Do NOT manually edit composer.json

Dev environment dependencies

composer require --dev phpunit/phpunit

Choosing a version

  • be precise
  • use caret operator
    • ^1.2 (>=1.2.0 <2.0.0)
    • sticks closer to semantic versioning
  • let the Composer decide about the version:
    composer require vendor/package

dev-master temptation

dev-master temptation

library without releases

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/you/package"
        }
    ],
    "require": {
        "you/package": "^1.0"
    }
}

avoid using those!

dev-master temptation

make use of aliases if available

{
    "name": "vendor/package",
    "extra": {
        "branch-alias": {
            "dev-master": "1.0.x-dev"
        }
    }
}
{
    "require": {
        "vendor/package": "1.0.*@dev"
    }
}

dev-master temptation

require inline aliases

{
    "require": {
        "vendor/package": "dev-bugfix as 1.0-dev"
    }
}

composer.lock

  • records the exact versions of dependencies in your project
  • MUST be put into VCS in case of applications
  • MAY be put into VCS in case of libraries

Useful commands

  • composer <command> -v|vv|vvv
  • composer show vendor/name
  • composer outdated

Autoloading

Composer should be the only mean for autoloading classes

{
    "autoload": {
        "psr-4": { "App\\": "src/" }
    },
    "autoload-dev": {
        "psr-4": { "App\\Tests\\": "tests/" }
    }
}

Define target platform

"config": {
    "platform": {
        "php": "5.6.29"
    }
}

Safer alternative for --ignore-platform-reqs

Scripts

{
    "scripts": {
        "test": "phpunit",
        "cs-fix": "php-cs-fixer fix --rules=@PSR2"
    }
}

Custom commands

composer test

Composer tips

By Nikola Poša

Composer tips

Few tips for using Composer the right way and getting most from it by using some of its less known features.

  • 1,514