Composer – Init, Install and update

Assuming that composer is installed on your machine what next?

If you do not have a composer.json file lets create one. In your command line ‘cd’ into your projects root folder. Then type

composer init

and answer the questions. Easy.

Look at your projects root directory and you will see a composer.json file. This is where you can add/remove packages, set namespaces, set files that are always load, run scripts, and lots of other good stuff.

Do you see a vendor/ directory? No? At this stage type

composer install

This actually ignores the .json file and reads or creates a composer.lock file then installs all the packages and dependencies required ( as well a bunch of other stuff – see the end of the post). The lock file is important when there are multiple developers/users it ensures that we/you are all using the exact same versions of installed packages.

Now lets pretend that you have cloned a project from GitHub that uses composer. You wont see a vendor/ directory but you will have a lock file.

composer install

Now you have a vendor/ directory and all is right with the world.

If you try and ┬árun install again it won’t do anything ( try it if you want )

If you want to add packages use the

composer require name\package

If you want to update the composer files and logs

composer update

Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file.

“A bunch of other stuff”

Composer can do a whole lot more. Including

  • Running scripts after installing, updating, etc
  • Autoload files. For example helper files with common functions
  • Pulling packages from GitHub. Great if you are writing your own
  • Lets you have a development environment and production sets of packages. E.g. so you can have PHPUnit just on your local machine.