Crash Course: PHP & Composer

I’ll be following the guide on https://getcomposer.org/doc/01-basic-usage.md.

Start off with downloading and setting up composer project dependency manager for PHP.

> php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
> php -r "if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
> php composer-setup.php
> php -r "unlink('composer-setup.php');"

It’ll create a composer.phar executable and a php folder in the current working directory. The next line will enable us to invoke composer.phar globally as composer by moving it into our bin directory.
>mv composer.phar /usr/local/bin/composer

Screenshot 2017-01-20 17.10.18.png

Great, now we have Composer installed and ready to go on our system. Next is to create the composer.json in our project directory, which is equivalent to npm’s package.json.

From here on out, we’ll be creating a package library to publish through a VCS like GitHub. This way, we can install our published library in our other projects through Composer (think of it as a module).

Let’s create the composer.json by hand first (without composer init).

In your project directory create a composer.json. Here, I added a name and a dependency requirement monolog/monolog: "1.0.*". Both name and dependency listing follow the naming convention: vendor/library for name and requirement. In here I named my project and added a package named monolog.

Screenshot 2017-01-20 18.50.53.png

Now, git init, add, commit,& push this composer.json in your https://github.com/vendor/library. Get out of that directory and now create a new test directory. In my case, “lib-test” was the name of my new directory. Create a new composer.json and refer back to your library (now on GitHub) similarly to how I did it.

Screenshot 2017-01-20 19.00.37.png

I got the name line confused the first couple of times around, but it definitely got better with practice. Save that composer.json file in your new project directory, and then issue this command in Terminal: composer install. You should see something like this.

Screenshot 2017-01-20 18.43.15.png

For future reference, try using the builtin composer init for initializing projects and libraries and composer update when you need to update or add dependencies in an existing project directory.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s