What is Composer?
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
Your dependencies will be installed in a folder called “vendor” inside your project folder and the libraries are managed on a per-project basis.
By default, nothing is installed globally but it does have support to install libraries on a global level. To install a library globally, you need to add the word “global” to the command in the terminal. You can install, remove, require, and update the libraries in the Composer home directory ( globally ), which is useful when you need a library for all your projects, for example, WordPress coding standards/ PHP Fixer.
The PHP Package Repository can be found at this URL.
How to Install Composer?
Linux
Installation can also be done locally or globally. When installing with the terminal command, there’s a chance that you might need to restart the terminal to test the installation.
Start by updating your package manager cache and installing the required dependencies, including php-cli (if not existent):
sudo apt update
sudo apt install php-cli unzip
Make sure you’re in your home directory, then retrieve the Composer installer using curl:
cd ~
curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php
Next, we’ll verify that the downloaded installer matches the SHA-384 hash for the latest installer found on the Composer Public Keys / Signatures page.
Using curl, fetch the latest signature and store it in a shell variable:
HASH=`curl -sS https://composer.github.io/installer.sig`
Now execute the following PHP code to verify that the installation script is safe to run:
php -r “if (hash_file(‘SHA384’, ‘/tmp/composer-setup.php’) === ‘$HASH’) { echo ‘Installer verified’; } else { echo ‘Installer corrupt’; unlink(‘composer-setup.php’); } echo PHP_EOL;”
The following command will download and install Composer as a system-wide command named composer, under /usr/local/bin:
sudo php /tmp/composer-setup.php –install-dir=/usr/local/bin –filename=composer
To test your installation, run:
composer
You should see the composer’s information like versions and terminal commands plus options
Windows
Download and run Composer-Setup.exe. It will install the latest Composer version and set up your PATH so that you can call Composer from any directory in your command line.
MacOS
One of the most easy ways to do this is using Homebrew.
Just by running “brew install composer”, and if you are using Oh My ZSH you can add the alias to composer.phar location to use it globally in the terminal.
Or you can use the terminal to run the commands:
sudo php -r “copy(‘https://getcomposer.org/installer’,’composer-setup.php’);”
php composer-setup.php
php -r “unlink(‘composer-setup.php’);”
Now test the installation with the terminal command “composer”
Note: You can also install Composer globally by manually specifying an install directory that is in your PATH:
php composer-setup.php –install-dir=/usr/local/bin –filename=composer
How to add Composer to a project?
If you are working on a plugin, just type in the plugin root in the terminal “composer init” and you will be asked several questions after that. This will define the composer.json, file which is required for composer management, and create it.
Everyone using the project will have the same composer.json and the same libraries installed. The Composer.json file needs to reach other devs, but it is not required for a live website.
Everyone on the same project using the same composer.json file, will mean that everyone is on the same page, using the same libraries, and the same versions. This will help a lot so that there are no discrepancies between the code.
Autoload classes and functions
An example of a simple composer.json that loads all the PHP classes from the specified folder but also autoloads files that contain helper functions.
You can specify multiple locations for autoload.
{
“name”: “vendor_name/my-project”,
“description”: “Project description”,
“minimum-stability”: “stable”,
“license”: “proprietary”,
“authors”: [
{
“name”: “mihaiirodiu”,
“email”: “email@example.com”
}
],
“require”: {
“ext-curl”: “*”,
“ext-json”: “*”
},
“autoload”: {
“classmap”: [“classes/”],
“files”: [“includes/global-helper-functions.php”, “includes/taxonomy-helper-functions.php”]
}
}
Then in the project “.php” file, I can just request the autoload.php file and access any classes that were added to autoload and any functions added to autoload, there is no need to include/require them again because the composer does that for you. Of course, If some new class is added you will need to inform the composer to update the autoload.
Simply run the command “composer dump-autoload” to refresh the autoload.php file.
For PHP Classes you can specify just the folder and the composer will create an autoload for all the PHP files.
For the helper function, you need to specify each and every PHP file.
It is better that in the future you create helper functions in helper classes so that they can be included in autoload.
How to Manage WordPress Core
You can manage your WordPress core installation with Composer by using John Bloch’s WordPress Core package. A standard required command would look something like this:
composer require johnpbloch/wordpress
How to Manage WordPress Themes and Plugins
Not only the WordPress core but also themes and plugins can be managed with Composer.
For example, https://wpackagist.org is a WordPress Packagist site that mirrors the WordPress plugin and theme directories as a Composer-compatible repository.
composer require wpackagist-plugin/akismet
How to Manage PHP Dependencies
Composer is particularly useful for managing PHP libraries that your project depends on.
For example, if you’re using PHPUnit for testing, you can add it with:
composer require –dev phpunit/phpunit
If you have a look on GitHub at libraries, most of them have composer installation instructions.
Advantages of using Composer
You can also use Composer to run scripts, such as tests or any other task. These scripts can be defined in the composer.json file under the scripts section.
Why would we run scripts using the composer?
- Convenience: Running scripts directly through Composer is quite easy as you just need to call them with composer run-script. You don’t need to remember long command lines, just the script name, which can be tailored to be descriptive of its purpose.
- Portability: Scripts defined in composer.json will work across all environments (local, staging, production) because they’re part of the project’s source code. This ensures that every team member is running the exact same scripts regardless of their local setup.
- Dependency Awareness: Composer scripts are aware of the dependencies that have been included in the project, thereby reducing issues that can arise due to differences in global and project-level dependencies.
- Consistency: Everyone using the project will use the same set of commands if they are defined in the composer.json. This reduces the chances of things going wrong because someone used a wrong or outdated command.
- Integration: These scripts can be easily integrated with other tools (like continuous integration systems) as the commands to be run are standardized and present in the composer.json file.
- Automation: You can automate many tasks like testing, linting, post-install commands, pre-commit checks…and so on, which increases productivity and reduces manual error.
- Platform Requirements Checks: Composer can prevent the installation of packages that can’t work on your system because of system requirements.
Is Composer the only tool you should use?
The answer is a clear NO.
While the composer is the best tool for specific tasks. There are task runners dedicated like Grunt, Gulp, and Webpack these might be more appropriate for heavy front-end JavaScript work.
Similarly, for more complex build and deployment processes, dedicated CI/CD ( Continuous Integration / Continuous Deployment ) tools might be better suited.
In the end, use the right tool for the job that needs to be done.
Also, in some cases, it can just be a personal preference.
Require and Require-Dev
- require: This section lists all the dependencies that are necessary for your project to run in all environments, including production.
These are the libraries and utilities that your project needs in order to execute correctly. When you or someone else runs Composer install, Composer will download and install these packages.
- require-dev: This section lists the dependencies that are not necessary for your project to run, but are useful during the development process. They are typically tools such as PHPUnit for testing, or PHPStan for static analysis. When you run composer install, these dependencies will also be installed.
However, when your project is being prepared for production and composer install –no-dev is executed, these require-dev packages will not be installed.
Autoload and Autoload-Dev
- autoload: This section maps your project’s namespaces to the directory structure of your project, making it easy to autoload your classes without having to require or include them manually. This autoload setting is used in all environments.
- autoload-dev: Similar to autoload, but it’s typically used for autoloading classes that are only used during development, like your project’s test classes. These classes won’t be available if you dump the Composer autoloader in a production environment using composer dump-autoload –no-dev.
Example 1
Execution of code linters
You can use a composer script to run code linters to ensure your code meets a certain quality before committing. You might have something like this:
“scripts”: {
“lint”: “phpcs”
}
Now you can lint your PHP files with:
composer run-script lint
Example 2
Running tests with PHPUnit
You can use Composer’s script directive to create a shortcut for running your PHPUnit tests. Add the following to your composer.json. “scripts” object:
“scripts”: {
“test”: “phpunit”
}
Then you can run tests more conveniently with:
composer run-script test
Example 3
Package from a VCS repository
You may want to pull a library from a VCS repository, like GitHub. With Composer, you can specify the VCS repository in your composer.json file. For example:
“repositories”: [
{
“type”: “vcs”,
“url”: “https://github.com/monolog/monolog”
}
],
“require”: {
“monolog/monolog”: “dev-master”
}
Example 4
Pulling in private repositories
If you have private libraries in your private VCS (either GitHub, BitBucket, GitLab or your own self-hosted system), you can include them easily. For example:
“repositories”: [
{
“type”: “vcs”,
“url”: “git@github.com:privateuser/privaterepo.git”
}
],
“require”: {
“privateuser/privaterepo”: “dev-master”
}
Example 5
Create custom-run script commands
You can add multiple actions that will be run one by one as long as there are no issues.
“scripts”: {
“run-phpcbf”: “phpcbf /path/to/your/directory –standard=WordPress-Core”,
“push-to-git”: “git push origin master”,
“wpr-push”: [
“@run-phpcbf”,
“@push-to-git”
]
}
And when you run the command `composer run-script wpr-push` or `composer wpr-push` the code from the specified folder will be fixed by phpcbf command then pushed to git.
This article was written by Mihai, Technical Team Leader at WPRiders.
Do you like this article? Share it and send us your feedback! Check out our articles page, where you might find other interesting posts. Also, if you want to learn more about business, check out the WPRiders Blog!