Using multiple PHP & Composer versions on MacOS

Refers to the previous post on how to install/upgrade PHP:

https://calvin.my/posts/install-upgrade-php-in-macos


Default Version

1) To check the default PHP version on your machine:

% which php
/opt/homebrew/opt/php@8.3/bin/php

2) With above configuration, whenever you enter "php blah blah" in your terminal, it executes php@8.3

3) If your application is built for a different PHP version (e.g. 8.1), running it with the default PHP might cause unexpected behaviors.

Using non-default versions

1) To check all the PHP versions you have on your machine:

% ls /opt/homebrew/opt | grep php
php
php@7.4
php@8.0
php@8.1
php@8.2
php@8.3

2) You can pick the correct version you need and run it with:

% /opt/homebrew/opt/php@8.1/bin/php <command>

% /opt/homebrew/opt/php@8.1/bin/php -v
PHP 8.1.29 (cli) (built: Jun  5 2024 05:51:57) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.29, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.29, Copyright (c), by Zend Technologies

PHP Composer

1) Composer is the tool in PHP to manage dependencies. For example, it is used in a Laravel application.

2) Composer is tied to PHP versions. That means setup composer with PHP 8.1 and later executing it using PHP 8.3, might not work properly.

3) In the composer installation guide, the steps create a global composer executable. When you complete the installation steps following the guide, you get a default composer compatible with your PHP.

4) You should do this once every time you install a newer PHP version on your machine.


Using non-default composer version

Now that you have replaced the default composer, what happens to the older projects?

1) Go to your project directory.

2) Follow the same composer installation guide, but replace all the "php" command with the exact version you need. e.g.

% php composer-setup.php

% /opt/homebrew/opt/php@8.1/bin/php composer-setup.php

3) This gives you a "composer.phar" executable in the project directory. 

4) Do not run the final step to copy this as default.

5) Now you can use the correct version of composer. e.g.

// This runs composer (for 8.1) using php 8.1
% /opt/homebrew/opt/php@8.1/bin/php composer.phar install

// This runs composer (for 8.3) using php 8.3
% composer install

Note: Add composer.phar into your gitignore so it won't go into your repository.


AI Summary
gpt-4o-2024-05-13 2024-09-30 11:23:36
This blog post guides MacOS users on managing multiple PHP and Composer versions. It covers checking default PHP versions, switching between different PHP versions, and handling Composer dependencies specific to these versions to ensure compatibility with various applications.
Chrome On-device AI 2024-10-04 22:03:27

Share Article