Using local packages as composer dependencies

Composer changed pretty much everything when it comes to including dependencies in PHP projects. No more SVN externals or copying large library folders into your project. This is really great, but there’s one thing I’ve been struggling to find a smooth process for; developing dependencies for your project.

When implementing your project, the need for some module, library, service provider or something else will arise, and sometimes you’ll have to implement it yourself. So, how to do that?

Possible solutions

  1. Implementing it inside your project, maybe in the library or source folder. Would work, but if you want to publish it [on packagist.org or somewhere else] as a separate package later on, you will make extra work for yourself.
  2. Publish the non-working package on packagist and push changes to you VCS. This is a really slow work process, as it requires you to push and do a composer update to see the changes.
  3. The other way™

The other way

I’ve found that setting up a repository with a relative file system reference is the easiest way. This way, you can have your dependency separate from the application and getting changes in the dependency is as simple as running composer update.

Example

Given the following folder structure;

package/composer.json

This simply defines a composer compatible package and is pretty straight forward. Now, let’s take a look at the composer.json file for the project, where the “magic” happens.

project/composer.json

The repositories part of the composer file is the only thing special. There are several repository types, but the VCS type refers to some sort of version control resource (locally or externally). The repository portion of the composer schema documentation notes that this could be svn, git or mercurial (hg).

For this example I’ve used a relative local path and git. As shown in the composer doumentation, using absolute paths or external URLs is also possible.

Running composer

At this point, a local git repo exists in the package folder and is now ready for inclusion in the project with composer.

That’s it! After this point, whenever a change is made to the package, commit your change and do a composer update. Like this;

Pro tip from the comment field

Gauthier Delamarre pointed out that it’s possible to specify the repository definition from composer.json into the users composer config. This is done by adding repository block to the file ~/.composer/config.json. As Gauthier points out, the benefit from doing it this way is that you won’t need to keep you environment specific paths for the repo in the composer.json, which allows you to commit and push it without thinking about messing everything up for other devs.

More documentation on the “home config”: https://getcomposer.org/doc/03-cli.md#composer-home-config-json

Read more from the Software engineering category
SUBSCRIBE TO OUR UPDATES
Menu