A few extra properties in .env, and a wee bit of code in the not-often-used 'port' entry does that switching in the database configuration file based on the $_SERVER['HOME'] entry, which is completely passive and doesn't require any special setup on the server. Works for PHPUnit tests too:
This solution may be a little hacky, but it works reliably. If there's a better way (there probably is), please let me know in the comments.
Also note the change from the default 'utf8' in 'charset' and 'collation'. This has nothing to do with port switching but has everything to do with MySql's handling of UTF8. There's a good writeup about it here, the gist of which is:
MySQL’s utf8 encoding is awkwardly named, as it’s different from proper UTF-8 encoding. It doesn’t offer full Unicode support.
Luckily, MySQL 5.5.3 (released in early 2010) introduced a new encoding called utf8mb4 which maps to proper UTF-8 and thus fully supports Unicode...
So I (we) should have been using MySQL 5.5.3 with that charset for at least the last 5 years.