Register your Magento 2 module as a Composer package with Packagist

Magento

/

Fri Dec 29 2017

Managing dependencies got a little bit better in Magento 2. It uses the PHP package manager Composer to keep track of what packages are needed and installed. I highly suggest you package your custom modules so you can take advantage if it. This write-up guides you through the process of packaging your Magento 2 module and connect it's Github repository to Packagist: Composer's default choice for hosting PHP packages.

Requirements

Your module needs to satisfy a few basic requirements before it will be accepted by Composer. You'll need to have a composer.json and a folder structure that suits it. A minimal composer.json would look like this:

{ "name": "vendor-name/module-name", "description": "Module description.", "type": "magento2-module", "version": "1.0.0", "authors": [ { "name": "Author Name", "email": "hello@example.com" } ], "autoload": { "files": [ "registration.php" ], "psr-4": { "VendorName\\ModuleName\\": "" } }

The name property should, by convention, contain the vendor and package name all in lowercase. Words should be separated by a dash and the package and vendor by a slash. The files property under autoload should contain your registration.php file, so Magento will be able to automatically register your module upon installation of the package. The psr-4 attribute sets up the PSR-4 autoloader which helps Composer place the files in the appropriate Magento directories. Nested within is a key-value pair with VendorName\\ModuleName\\ as key, and an value that points to the directory that contains the module source files. In this case it is empty, signalling it is the root directory of the repository. A Magento 1 folder structure (app/code/VendorName/ModuleName/) is no longer necessary.

Setting up Github and Packagist

If it isn't already, make sure your source code is hosted at Github. It is important to draft a release for your module so Composer knows there is a stable version available.

Next, you should create a Packagist account. Once you've done that, submit your repo to Packagist. To keep your Composer package in sync, head over to the settings page of your Github repository and open the integrations & services tab.

Add the packagist service and fill out your username and API token. You can find your token over at your Packagist profile page. Test your connection by clicking the test service in the top right of the Github settings page.

That's it! You should now be able to install your module by using the following command.

composer require vendor-name/module-name

Enjoy!