Daily Archives: 26th of January 2023

composer šŸ§” phar

It bothered me for a long time that installing tools via composer cluttered my projects with unnecessary dependencies and also bind my code to the dependencies of my development toolchain and vice-versa.

The easy way to solve that was to use phar-files for the tools I am using in my development chain. So tools like phpunit, phpstan, psalm or phpcs/phpcbf. All of these can be installed via composer require --dev – but also via phive install.

The trouble though when using the phar-files was, that composer didn’t know about them and whenever I wanted to use a plugin for one of those tools, composer didn’t know that the tool was already there and so installed the tool again. Which wasn’t helpful!

I was thinking about multiple ways to handle that. Like a plugin for composer to remove installed PHAR-files from the internal resolver-tree and what other ideas I had. All of these didn’t really work out.

Until a few days it hit me: composers replace config-option!

So what did I do:

After installing my tool – in this case php-codesniffer – via phive install phpcs --copy I created a new composer.json file in the .phive-folder with the following content:

{
    "name": "myproject/phive_stuff",
    "description": "A replacement package for phars",
    "minimum-stability": "stable",
    "license": "MIT",
    "replace" : {
        "squizlabs/php_codesniffer": "*"
    }
}

Now I added this code to my projects composer.json file:

{
    "repositories": [{
        "type": "path",
        "url": ".phive/"
    }]
}

Then all that was left to do was to require the new package via

composer require --dev myproject/phive_stuff 

With all that done I can now install plugins for php-codesniffer via

composer require --dev phpcompatibility/php-compatibility

and composer will realize that php-codesniffer is already installed and not install it again.

Caveat

This has some caveats though! For example there are two tools phpcs and phpcbf that need to be installed via phive while requiring squizlabs/php-codesniffer will install both of them.

Due to the way phive works, the binaries are by default linked into the project from a main folder outside the project which can break when using docker. That’s why I usually call phive with the --copy flag as that actually adds a copy of the phar to the tools -folder.

Due to this linking phpcs suddenly created its config-file in that shared folder which had some unexpected sideeffects. When using --copy the confi is added by default to the tools folder.

So there might be some extra work necessary when using PHARs. But at least it works now šŸ˜

Further ideas

My main idea now was to automate this manual process as that is something that can automatically done by phive when installing (or updating) a tool.

Would that something that helps others as well? Feel free and leave your comment in the feature-request on github