同时开发多个项目时,可能会对PHP版本有不同要求,这篇文章教你怎么使用Homebrew安装多个php-cli、php-fpm,并可以随时切换

虽然使用Docker来实现环境隔离,其实是个更好的方案。但在本地开发环境中,Docker的内存占用、启动时间、有时会抽风,所以也有很多小伙伴直接使用Homebrew来安装PHP

安装默认版本的PHP

直接安装不带版本号的PHP,默认安装的是最新版本

1
brew install php

更好的方式是即使安装最新版,也带上版本号,比如现在更新到8.1

1
brew install php@8.1

因为这样通过brew services list查看所有PHP时,可以更清晰

安装低版本的PHP

直接使用brew安装发现报错

1
brew install php@7.1
1
php@7.1 has been disabled because it is deprecated upstream!

根据https://stackoverflow.com/questions/70237219/how-to-install-php-7-2-on-macos-big-sur-using-homebrew的解释:

php低版本已被Hombrew核心存储库删除,可使用以下命令安装php低版本

1
2
brew tap shivammathur/php
brew install shivammathur/php/php@7.1

安装后修改7.1的监听端口号,这样做的目的是可以同时启动多个php-fpm。如果没这个需求,可以不修改

1
2
vim /opt/homebrew/etc/php/7.1/php-fpm.d/www.conf
listen = 127.0.0.1:9071

启动php7.1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
brew services start php@7.1

➜  brew services list
Name    Status  User      File
nginx   started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
php@5.6 started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.php@5.6.plist
php@7.1 started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.php@7.1.plist
php@7.4 started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.php@7.4.plist
php@8.2 started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.php@8.2.plist
redis   started sunhuawei ~/Library/LaunchAgents/homebrew.mxcl.redis.plist

看到对应版本现实started说明启动成功了,想使用7.1版本的php-fpm,使用9071端口即可

切换PHP版本

比如从php@8.1切换到php@7.1

1
2
3
4
5
6
7
8
brew unlink php@8.1
brew link php@7.1

➜  ~ PHP -v
PHP 7.1.33 (cli) (built: Dec  8 2022 08:12:40) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.1.33, Copyright (c) 1999-2018, by Zend Technologies