17 Tips for Using Composer Efficiently

Martin Hujer has collected 17 tips for using composer efficiently, and then added a few more after receiving the feedback on the blog post.  I was familiar with most of these, but there are still a few that are new to me.

Tip #7: Run Travis CI builds with different versions of dependencies

I knew about the Travis CI matrix configuration, but used it only for other things.  I’ll be looking into extending it for the composer tests shortly.

Tip #8: Sort packages in require and require-dev by name

This is a great tip!  I read the composer documentation several times, but somehow I missed this option.  It is especially useful for the the way we manage projects at work (waterfall merges from templates and basic projects into more complex ones).

Tip #9: Do not attempt to merge composer.lock when rebasing or merging

Here, I’m not quite sure about the whole bit on git attributes.  Having git try to merge and generate a conflict creates a very visible problem.  Avoiding the merge might hide things a bit until they popup much later in the CI.  I guess I’ll have to play around with this to make up my mind.

Tip #13: Validate the composer.json during the CI build

This is a great tip!  I had plenty of issues with composer validations in the past.  Currently, we have a couple of unit tests that make sure that composer files are valid and up-to-date.  Using a native mechanism for that is a much better option.

Tip #15: Specify the production PHP version in composer.json

This sounds like an amazing feature which I once again missed.  Especially now that we are still migrating some projects from PHP 5.6 to PHP 7.1, and have to sort out dependency conflicts between the two versions.

Tip #20: Use authoritative class map in production

We are already almost doing it, but it’s a good opportunity to verify that we utilize the functionality correctly.

 

Dependency Management and WordPress: A Proposal

I came across this article – “Dependency Management and WordPress: A Proposal“, which provides an excellent overview of some of the recent developments and discussions in the area of composer integration with WordPress, and even more generically, some of the issues around dependency management in an ecosystem as large and complex as that of WordPress.

It’s been a while since I checked what’s going on in this area.  A couple of years back, I linked to an article that shows a way to use composer with WordPress, and since then I’ve built something similar for our use at work.

But it’s good to see that the problem is not tossed and forgotten, and that there are some very smart people still trying to work it out.

composer-git-hooks – manage git hooks in your composer config

composer-git-hooks looks awesome!  From the project page description:

Manage git hooks easily in your composer configuration. This package makes it easy to implement a consistent project-wide usage of git hooks. Specifying hooks in the composer file makes them available for every member of the project team. This provides a consistent environment and behavior for everyone which is great.

Validating JSON against schema in PHP

GitHub was rather slow yesterday, which affected the speed of installing composer dependencies (since most of them are hosted on GitHub anyway).  Staring at a slowly scrolling list of installed dependencies, I noticed something interesting.

...
  - Installing seld/jsonlint (1.6.0)
  - Installing justinrainbow/json-schema (5.1.0)
...

Of course, I’ve heard of the seld/jsonlint before.  It’s a port of zaach/jsonlint JavaScript tool to PHP, written by Jordi Boggiano, aka Seldaek, the genius who brought us composer dependency manager and packagist.org repository.

But JSON schema? What’s that?

The last time I heard the word “schema” in a non-database context, it was in the XML domain.  And I hate XML with passion.  It’s ugly and horrible and should die a quick death.  The sooner, the better.

But with all its ugliness, XML has does something right – it allows the schema definition, against which the XML file can be validated later.

Can I have the same with JSON?  Well, apparently, yes!

justinrainbow/json-schema package allows one to define a schema for what’s allowed in the JSON file, and than validate against it.  And even more than that – it supports both required values and default values too.

Seeing the package being installed right next to something by Seldaek, I figured, composer might be using it already.  A quick look in the repository confirmed my suspicion.  Composer documentation provides more information, and links to an even more helpful JSON-Schema.org.

Mind.  Officially.  Blown.

At work, we use a whole lot of configuration files for many of our projects.  Those files which are intended for tech-savvy users, are usually in JSON or PHP format, without much validation attached to them.   Those files which are for non-technical users, usually rely on even simpler formats like INI and CSV.  I see this all changing and improving soon.

But before any of that happens, I need to play around with these amazing tools.  Here’s a quick first look that I did:

  1. Install the JSON validator: composer require justinrainbow/json-schema
  2. Create an example config.json file that I will be validating.
  3. Create a simple schema.json file that defines what is valid.
  4. Create a simple index.php file to tie it altogether, mostly just coping code from the documentation.

My config.json file looks like this:

{
	"blah": "foobar",
	"foo": "bar"
}

My schema.json file looks like this:

{
	"type": "object",
	"properties": {
		"blah": {
			"type": "string"
		},
		"version": {
			"type": "string",
			"default": "v1.0.0"
		}
	}
}

And, finally, my index.php file looks like this:

<?php
require_once 'vendor/autoload.php';

use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;

$config = json_decode(file_get_contents('config.json'));
$validator = new Validator; $validator->validate(
	$config,
	(object)['$ref' => 'file://' . realpath('schema.json')],
	Constraint::CHECK_MODE_APPLY_DEFAULTS
);

if ($validator->isValid()) {
	echo "JSON validates OK\n";
} else {
	echo "JSON validation errors:\n";
	foreach ($validator->getErrors() as $error) {
		print_r($error);
	}
}

print "\nResulting config:\n";
print_r($config);

When I run it, I get the following output:

$ php index.php 
JSON validates OK

Resulting config:
stdClass Object
(
    [blah] => foobar
    [foo] => bar
    [version] => v1.0.0
)

What if I change my config.json to have something invalid, like an integer instead of a string?

{
	"blah": 1,
	"foo": "bar"
}

The validation fails with a helpful information:

$ php index.php 
JSON validation errors:
Array
(
    [property] => blah
    [pointer] => /blah
    [message] => Integer value found, but a string is required
    [constraint] => type
)

Resulting config:
stdClass Object
(
    [blah] => 1
    [foo] => bar
    [version] => v1.0.0
)

This is great. Maybe even beyond great!

The possibilities here are endless.  First of all, we can obviously validate the configuration files.  Secondly, we can automatically generate the documentation for the supported configuration options and values.  It’s probably not going to be super fantastic at first, but it will cover ALL supported cases and will always be up-to-date.  Thirdly, this whole thing can be taken to the next level very easily, since the schema files are JSON themselves, which means schema’s can be generated on the fly.

For example, in our projects, we allow the admin/developer to specify which database field of a table is used as display field (in links and such).  Only existing database fields should be allowed.  So, we can generate the schema with available fields on project deployment, and then validate the user configuration against his particular database setup.

There are probably even better ways to utilize all this, but I’ll have to think about it, which is not easy with the mind blown…

Update (March 16, 2017): also have a look at some alternative JSON Schema validators.  JSON Guard might be a slightly better option.

Composer require inline alias

Here’s a feature of composer that I didn’t know about until a few days ago – require inline alias.  Here’s the example from the documentation:

{
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/you/monolog"
        }
    ],
    "require": {
        "symfony/monolog-bundle": "2.0",
        "monolog/monolog": "dev-bugfix as 1.0.x-dev"
    }
}

This is super useful when you have dependencies in your project that require a particular version of a third-party library or plugin, and you want to try a branch of that library or plugin. Switching to the branch alias doesn’t solve the problem, as everything that has version constraints on that requirement, will complain. With inline alias, you can alias a particular branch of the dependency as a particular version.

With inline alias, composer will fetch the branch that you want, but will assume that that branch works as a particular version that you specify, and thus satisfy all the other dependencies that require that particular version.

In my particular case, I was working on the CakePHP-based application, which was using a few CakePHP plugins (installed via composer).  Those plugins require CakePHP v3+.  I wanted to test a branch of CakePHP which had a particular fix I was interested in, but without disabling all the plugins.  Switching my application’s composer to require a branch dissatisfied all the plugins, as now composer didn’t know if the branch that I am requiring is of the CakePHP v3 or not.  Aliasing the branch to v3.4.1 (current stable version at the time) worked like a charm.