How to Set Up PHP Composer in MacOS

Updated: January 12, 2024 By: Guest Contributor Post a comment

Introduction

PHP is a widely-used open-source scripting language, and Composer is a dependency manager for PHP. Installing Composer on your MacOS system can greatly improve your PHP development workflow. In this tutorial, you’ll learn how to set up PHP Composer on MacOS and begin using it for PHP development.

Prerequisites

  • A MacOS computer
  • PHP 5.3.2 or above (PHP 7 or 8 recommended)
  • Command Line Tools for Xcode or Xcode

The Steps

Step 1: Install PHP

Although MacOS comes with PHP pre-installed, the version might not be up to date. You can check your current PHP version by typing the following command into the terminal:

php -v

If you need to update PHP, you can use Homebrew, a package manager for MacOS:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
brew install php

Step 2: Ensure Proper PHP Configuration

To work correctly with Composer, PHP must be properly configured. Open the php.ini file and make sure the following settings are correctly set:

memory_limit = 1G
date.timezone = Your_Prefered_Timezone

Step 3: Install Composer

Installing Composer is straightforward. You’ll be using the installation script provided on the Composer website. In your terminal, run:

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

In the second command, replace <expectedSignature> with the latest signature found on the Composer’s download page.

Step 4: Make Composer Globally Accessible

To use Composer from anywhere on your system, you should move the ‘composer.phar’ file to a directory in your PATH. One common location is ‘/usr/local/bin’.

mv composer.phar /usr/local/bin/composer

Verify the installation by typing:

composer

Step 5: Use Composer in Your PHP Projects

With Composer installed, you can now manage dependencies for your PHP projects. Navigate to your project’s directory and run:

composer require vendor/package

Replace ‘vendor/package’ with the package you wish to install.

Step 6: Updating Dependencies

Composer makes updating dependencies a breeze. The ‘composer.json’ file in your project’s root holds the required packages. To update them, run:

composer update

Step 7: Autoloading

With Composer, you can autoloader to include PHP files automatically:

require 'vendor/autoload.php';

Conclusion

You now have PHP Composer set up on your MacOS system. This setup will help you manage project dependencies more efficiently, thus improving your development workflow.

For more information, consult the official Composer documentation.