📜 ⬆️ ⬇️

Mastering Composer: Tips and Tricks for Using

I propose to readers of Habrakhabr a translation of the article “Mastering Composer - Tips and Tricks” by Bruno Skvorc.

Composer logo

Composer revolutionized package management in PHP and helped developers around the world create framework-independent and shared code. But still few people go beyond the basics of its functionality, so this article will try to highlight some useful techniques for its use.

Global Setup (Global)


Although this option is available described in the documentation, Composer can (and in most cases should) be set globally. Global installation means that instead of:
')
php composer.phar somecommand 

In any project you can simply enter:

 composer somecommand 

This makes it very easy to create new projects (for example, using the create-project command) anywhere in your file system.

To install Composer globally, follow these instructions .

Correct installation of dependencies


When reading introductory instructions or README files, many will write you something like:
Just add the following to your composer.json file :
 {
     "require": {
         "myproject": "someversion"
     }
 }


But this approach has several drawbacks. First, a simple copy-paste can lead to errors. Secondly, for a newbie, it may not be obvious where to put this code if it already has an extensive composer.json file, and this also leads to an error. Finally, some people will deal with Composer for the first time, and possibly face the command line for the first time. Therefore, it will be good practice to cover all kinds of cases in which beginners may feel insecure (do they have a graphic editor or will they use the command line? If the second is, does the text editor are installed in it, and if so, which one? Do you explain file editing procedure? What if the composer.json file does not yet exist in the project? Do you also describe the principle of creating a new file?).

The best way to add a new dependency to the composer.json file is to use the require command:

 composer require somepackage/somepackage:someversion 

This will add everything you need to the dependency file, bypassing manual intervention.

If you need to add packages to the require-dev section, add the --dev option to the command :

 composer require phpunit/phpunit --dev 

Also, the require command supports adding multiple packages at the same time; to do this, simply separate them with a space.

Lock files


The composer.lock file saves the current list of installed dependencies and their versions. Thus, at the time when the dependency versions are already updated, other people who will clone your project will receive the same versions. This allows you to make sure that everyone who gets your project has a “batch environment” identical to the one you used during development, and helps to avoid errors that might arise from updating versions.

The file composer.lock should almost always be added to the version control system ( not always ).

Also, the composer.lock file contains the hash of the composer.json file, so if you even just update the data about the author of the project, you will receive a warning that the lock file does not correspond to the .json file. In this case, the composer update --lock command will help, which will update only the lock file itself, without touching anything else.

Versioning


When specifying acceptable package versions, you can use exact matching ( 1.2.3 ), ranges with comparison operators ( <1.2.3 ), combinations of these operators ( > 1.2.3 <1.3 ), “last available” ( 1.2. * ), Tilde symbol ( ~ 1.2.3 ) and the caret ( ^ 1.2.3 ).

The last two instructions are worthy of a separate explanation:

Except when you know that you need a specific version of a package, I recommend always using ~ 1.2.3 format - this is the safest choice.

Local and global configuration


The default parameter values ​​are not set in stone. A detailed description of the possible configuration parameters ( config ), see the link .

For example, specifying:
 {
     "config": {
         "optimize-autoloader": true
     }
 }

you force Composer to optimize the classmap after each installation or update of packages (or, in other words, whenever a class autoload file is generated). This is a bit slower than creating a default autoloader, and slows as the project grows.

Another useful parameter might be cache-files-maxsize . In large projects (like eZ Publish or Symfony), the cache can fill up pretty quickly. Increasing the size of the cache to allow Composer to work quickly longer.

Please note that the configuration parameters can be set globally, and in this case will affect all projects (see config ). For example, to globally set the cache size parameter, you must either edit the file ~ / .composer / config.json , or run:

 composer config --global cache-files-maxsize "2048MiB" 


Profiling and verbose output (verbose)


If you add the --profile parameter to any command when using Composer on the command line, the output will contain not only the final result, for example:

 [174.6MB/54.70s] Memory usage: 174.58MB (peak: 513.47MB), time: 54.7s 

But also at the beginning of each line of output the command execution time and the used memory size will be added:

 [175.9MB/54.64s] Installing assets for Sensio\Bundle\DistributionBundle into web/bundles/sensiodistribution 

I use this option to define “slow” packages and to monitor the improvement or degradation of performance on different versions of PHP .

Like the previous one, the --verbose option will cause Composer to display more information about each operation being performed, letting you know exactly what is happening at the moment. Some people even install composer --verbose --profile with the default alias of the composer command.

Custom sources


If your project is not yet on Packagist, sometimes you just need to install the package from GitHub (for example, if the package is still under development). For this see our guide .

When you have your own version of a popular package on which your project depends, you can use custom sources in conjunction with contextual pseudonyms (inline aliasing) to substitute your own branch for a public package, as described here by Matthieu Napoli.

Acceleration Composer


Using the excellent method described by Mark Van Eijk , you can speed up Composer execution by calling it through HHVM.

Another way is by using the --prefer-dist option, when installed, Composer will download stable, packed versions of the project, instead of cloning from the version control system (which is much slower). This parameter is used by default, so you do not need to enable it on stable projects. If you need to load a project from source, use the --prefer-source parameter. For more information, see the install section here .

Reducing the size of the Composer project


If you are a developer of “Composer-friendly” projects, this part will also interest you. On this post in Reddit , you can use the .gitattributes file to ignore some files and folders while packing the package for the --prefer-dist mode.
 / docs export-ignore
 / tests export-ignore
 /.gitattributes export-ignore
 /.gitignore export-ignore
 /.travis.yml export-ignore
 /phpunit.xml export-ignore

How it works? When you upload a project to GitHub, it automatically makes available the “Download zip” link, with which you can download your project archive. Moreover, Packagist uses these automatically generated archives to download dependencies with the --prefer-dist option, which it then locally unzips (much faster than cloning project source files). If you add tests, documentation and other files that are not related to the logic of the project, the specified archives will not contain them, becoming much easier.

In this case, people who want to debug your library or run tests will need to specify the parameter --prefer-source .

PhpLeague took this approach and included it in its “package skeleton ”, so any project based on it would automatically be “dist friendly” .

Show


If you suddenly forget which version of PHP or its extensions you are using, or you need a list of all installed projects (with a description of each) with their versions, you can use the show command with the --platform ( -p ) and --installed ( -i ) options ):

composer show --installed
 $ composer show --installed behat/behat v3.0.15 Scenario-oriented BDD framework for PHP 5.3 behat/gherkin v4.3.0 Gherkin DSL parser for PHP 5.3 behat/mink v1.5.0 Web acceptance testing framework for PHP 5.3 behat/mink-browserkit-driver v1.1.0 Symfony2 BrowserKit driver for Mink framework behat/mink-extension v2.0.1 Mink extension for Behat behat/mink-goutte-driver v1.0.9 Goutte driver for Mink framework behat/mink-sahi-driver v1.1.0 Sahi.JS driver for Mink framework behat/mink-selenium2-driver v1.1.1 Selenium2 (WebDriver) driver for Mink framework behat/sahi-client dev-master ce7bfa7 Sahi.js client for PHP 5.3 behat/symfony2-extension v2.0.0 Symfony2 framework extension for Behat behat/transliterator v1.0.1 String transliterator components/bootstrap 3.3.2 The most popular front-end framework for developing responsive, mobile first projects on the web. components/jquery 2.1.3 jQuery JavaScript Library doctrine/annotations v1.2.4 Docblock Annotations Parser doctrine/cache v1.4.1 Caching library offering an object-oriented API for many cache backends doctrine/collections v1.3.0 Collections Abstraction library doctrine/common v2.5.0 Common Library for Doctrine projects doctrine/dbal v2.5.1 Database Abstraction Layer doctrine/doctrine-bundle v1.4.0 Symfony DoctrineBundle doctrine/doctrine-cache-bundle v1.0.1 Symfony2 Bundle for Doctrine Cache doctrine/inflector v1.0.1 Common String Manipulations with regard to casing and singular/plural rules. doctrine/instantiator 1.0.4 A small, lightweight utility to instantiate objects in PHP without invoking their constructors doctrine/lexer v1.0.1 Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers. egulias/listeners-debug-command-bundle 1.9.1 Symfony 2 console command to debug listeners ezsystems/behatbundle dev-master bd95e1b Behat bundle for help testing eZ Bundles and projects ezsystems/comments-bundle dev-master 8f95bc7 Commenting system for eZ Publish ezsystems/demobundle dev-master c13fb0b Demo bundle for eZ Publish Platform ezsystems/demobundle-data v0.1.0 Data for ezsystems/demobundle ezsystems/ezpublish-kernel dev-master 3d6e48d eZ Publish API and kernel. This is the heart of eZ Publish 5. ezsystems/platform-ui-assets-bundle v0.5.0 External assets dependencies for PlatformUIBundle ezsystems/platform-ui-bundle dev-master 4d0442d eZ Platform UI Bundle ezsystems/privacy-cookie-bundle v0.1 Privacy cookie banner integration bundle into eZ Publish/eZ Platform fabpot/goutte v1.0.7 A simple PHP Web Scraper friendsofsymfony/http-cache 1.3.1 Tools to manage cache invalidation friendsofsymfony/http-cache-bundle 1.2.1 Set path based HTTP cache headers and send invalidation requests to your HTTP cache guzzle/guzzle v3.9.3 PHP HTTP client. This library is deprecated in favor of https://packagist.org/packages/guzzlehttp/guzzle hautelook/templated-uri-bundle 2.0.0 Symfony2 Bundle that provides a RFC-6570 compatible router and URL Generator. hautelook/templated-uri-router 2.0.1 Symfony2 RFC-6570 compatible router and URL Generator imagine/imagine 0.6.2 Image processing for PHP 5.3 incenteev/composer-parameter-handler v2.1.0 Composer script handling your ignored parameter file instaclick/php-webdriver 1.0.17 PHP WebDriver for Selenium 2 jdorn/sql-formatter v1.2.17 a PHP SQL highlighting library knplabs/knp-menu v1.1.2 An object oriented menu library knplabs/knp-menu-bundle v1.1.2 This bundle provides an integration of the KnpMenu library kriswallsmith/assetic v1.2.1 Asset Management for PHP kriswallsmith/buzz v0.13 Lightweight HTTP client league/flysystem 0.5.12 Many filesystems, one API. liip/imagine-bundle 1.2.6 This Bundle assists in imagine manipulation using the imagine library monolog/monolog 1.13.1 Sends your logs to files, sockets, inboxes, databases and various web services nelmio/cors-bundle 1.3.3 Adds CORS (Cross-Origin Resource Sharing) headers support in your Symfony2 application ocramius/proxy-manager 0.5.2 A library providing utilities to generate, instantiate and generally operate with Object Proxies oneup/flysystem-bundle v0.4.2 Integrates Flysystem filesystem abstraction library to your Symfony2 project. pagerfanta/pagerfanta v1.0.3 Pagination for PHP 5.3 phpdocumentor/reflection-docblock 2.0.4 phpspec/prophecy v1.4.1 Highly opinionated mocking framework for PHP 5.3+ phpunit/php-code-coverage 2.0.16 Library that provides collection, processing, and rendering functionality for PHP code coverage information. phpunit/php-file-iterator 1.4.0 FilterIterator implementation that filters files based on a list of suffixes. phpunit/php-text-template 1.2.0 Simple template engine. phpunit/php-timer 1.0.5 Utility class for timing phpunit/php-token-stream 1.4.1 Wrapper around PHP's tokenizer extension. phpunit/phpunit 4.6.4 The PHP Unit Testing framework. phpunit/phpunit-mock-objects 2.3.1 Mock Object library for PHPUnit psr/log 1.0.0 Common interface for logging libraries qafoo/rmf 1.0.0 Very simple VC framework which makes it easy to build HTTP applications / REST webservices sebastian/comparator 1.1.1 Provides the functionality to compare PHP values for equality sebastian/diff 1.3.0 Diff implementation sebastian/environment 1.2.2 Provides functionality to handle HHVM/PHP environments sebastian/exporter 1.2.0 Provides the functionality to export PHP variables for visualization sebastian/global-state 1.0.0 Snapshotting of global state sebastian/recursion-context 1.0.0 Provides functionality to recursively process PHP variables sebastian/version 1.0.5 Library that helps with managing the version number of Git-hosted PHP projects sensio/distribution-bundle v3.0.21 Base bundle for Symfony Distributions sensio/framework-extra-bundle v3.0.7 This bundle provides a way to configure your controllers with annotations sensio/generator-bundle v2.5.3 This bundle generates code for you sensiolabs/security-checker v2.0.2 A security checker for your composer.lock swiftmailer/swiftmailer v5.4.0 Swiftmailer, free feature-rich PHP mailer symfony-cmf/routing 1.3.0 Extends the Symfony2 routing component for dynamic routes and chaining several routers symfony/assetic-bundle v2.6.1 Integrates Assetic into Symfony2 symfony/monolog-bundle v2.7.1 Symfony MonologBundle symfony/swiftmailer-bundle v2.3.8 Symfony SwiftmailerBundle symfony/symfony v2.6.6 The Symfony PHP framework tedivm/stash v0.12.3 The place to keep your cache. tedivm/stash-bundle v0.4.2 Incorporates the Stash caching library into Symfony. twig/extensions v1.2.0 Common additional features for Twig that do not directly belong in core twig/twig v1.18.1 Twig, the flexible, fast, and secure template language for PHP white-october/pagerfanta-bundle v1.0.2 Bundle to use Pagerfanta with Symfony2 whiteoctober/breadcrumbs-bundle 1.0.2 A small breadcrumbs bundle for Symfony2 zendframework/zend-code 2.2.10 provides facilities to generate arbitrary code using an object oriented interface zendframework/zend-eventmanager 2.2.10 zendframework/zend-stdlib 2.2.10 zetacomponents/base 1.9 The Base package provides the basic infrastructure that all packages rely on. Therefore every component relies on this package. zetacomponents/feed 1.4 This component handles parsing and creating RSS1, RSS2 and ATOM feeds, with support for different feed modules (dc, content, creativeCommons, geo, iTunes). zetacomponents/mail 1.8.1 The component allows you construct and/or parse Mail messages conforming to the mail standard. It has support for attachments, multipart messages and HTML mail. It also interfaces with SMTP to send mail or IMAP, P... zetacomponents/system-information 1.1 Provides access to common system variables, such as CPU type and speed, and the available amount of memory. 


Rehearsals (Dry Runs)


To simply see if the installation of new dependencies will succeed, you can use the --dry-run option for the install and update commands. Composer in this case will display all potential problems without directly executing the command itself. There will be no real changes in the project. This technique is great for testing complex dependencies and setting up changes before actually making them.

 composer update --dry-run --profile --verbose 

Project creation


Last but not least, what we have to mention is the create-project command .

The project creation command takes as its argument the name of the package, which it then clones and executes composer install inside it. This is great for project initialization - you no longer need to search for the Url of the required package on GitHub, clone it, go to the folder yourself, and execute the install command.

Major projects such as Symfony and Laravel already use this approach to initialize their “skeleton” applications, and many others are also joining.

For example, in Laravel it is used as follows:

 composer create-project laravel/laravel --prefer-dist --profile --verbose 

Two more parameters can be passed to the create-project command: the path to which the project should be installed (if not specified, the package name is used), and the version (the latter will be used if not specified).

Conclusion


I hope this list of tips and tricks of use has been useful to you. If we have missed something, tell us about it and we will update the article. And remember, if you forget any commands or options, just look at the cheat sheet . Happy Composing!

Source: https://habr.com/ru/post/258891/


All Articles