Requiring a Forked Repo with Composer

July 9, 2022
by Ben Croker

If you ever find yourself having to modify a Craft plugin, or any composer package for that matter, then you can do so using a fork. A fork is a copy of a repository that you manage. Forked repositories let you make changes to a package without affecting the original repository.

Requiring a forked repo with composer

You could of course simply copy the source code into your own new repository, but forking a repository allows you to submit pull requests (suggested changes) to the original repository and to sync changes made in the original repository with your fork.

Creating a Fork #

Creating a new fork using GitHub is as simple as clicking the Fork” button in the repository that you want to fork.

Creating a new fork using GitHub

Once forked, you can modify any of the files in the forked repository, since you own it.

When forking a Craft CMS plugin, make sure that the license permits you to do so, that you have permission from the developer to do so, or that you respect the terms of the license and pay any license fees.

Requiring a Forked Repo #

To use the forked repo in your Craft CMS project, you’ll need to tell Composer where to find it. To do so, add a VCS (version control system) repository to your project’s main composer.json file, using the URL of your forked repository.

"repositories": [
  {
    "type": "vcs",
    "url": "https://github.com/bencroker/craft-blitz"
  }
],

It is a good idea to create and work in a custom branch of your fork, so that you can later submit a pull request to the original repository. In your composer.json file, you should then reference your custom branch name in the require field, prefixed with dev-. So if you named your custom branch bugfix, you would update the require field as follows.

"require": {
  "putyourlightson/craft-blitz": "dev-bugfix"
},

Note that you do not change the repository name in the require statement, only the branch prefixed with dev-. You still reference the original repository (putyourlightson/craft-blitz), not your personal fork (bencroker/craft-blitz).

Run composer update and your forked repo will be loaded in place of the original. For more details on this, as well as using private repositories, read the Composer docs.

Working with Forked Repos #

Finally, you can sync your fork to keep it up-to-date with the upstream repository or create a pull request to propose changes to the original repository, all of which is well documented at the links provided.