How to Override a Composer Dependency so it Pulls From Your Branch

Ran into a situation this week where I needed to fix and slightly customize a dependency of a dependency. This was for a Laravel project that uses Composer to manage dependencies.  Since I’m using Composer everything in /vendor is managed by Composer and is off limits to code changes.

Composer

I need to get things launched – with a fix bugs first attitude. Who has time to wait for a pull request to get approved? Not me.

Thankfully there is a way to tell Composer to override a dependency and use your fork instead of the main provider’s.

1) Make a fork of the repo. 

Do your amazing high touch changes in a branch in your fork. Going forward in this example, let’s say your branch is called myfix.

Side note – in my case, the original project was in github, but I wanted my fork to live in bitbucket. So I followed these steps. It’s not technically a fork but it is still connected to the original repo.  Just make sure the fork / copy has the exact same project name as the original.

2) Update your composer.json file.

"repositories": [
    {
        "type": "git",
        "url": "https://bitbucket.org/myuser/thedependency/"
    }
],
"require": {
    "originalowner/thedependency": "dev-myfix as 5.3.0"
},

The repositories section is where you tell composer about your repo (where the myfix branch lives). Composer will automatically scan for branches in that repository.

The require section “dev-myfix as 5.3.0” part was confusing to me at first so I’ll explain what it is doing.

Your branch is named myfix, but trust me, write in dev-myfix.  That tells composer it is a custom branch (dev- is a composer convention).  Then after dev-myfix the as 5.3.0 part creates an inline alias that allows Composer to satisfy the parent dependency, or anything else in your project that needs thedependency 5.3.0.   In this case 5.3.0 is an example. Make sure the version alias you type into your composer.json files matches what your project needs. You can find that out by running composer show.

3) Re-install dependencies:

  1. Run composer clearcache otherwise it will supply thedependency from a copy in your local cache that points to the original repo. That’s not what you want.
  2. In my case, deleting the composer.lock file was safe and this cleared the way for the next step.
  3. Run composer install

 

This entry was posted in Application Development and tagged , , . Bookmark the permalink.

Comments are closed.