Tuesday, December 01, 2015

Switching database ports on-the-fly for Artisan, PHPUnit

One of the minor (really minor) annoyances of using Artisan in a Homestead/Vagrant environment is having to remember to run commands that interact with a database on the server, since that's where the database lives. It's possible to run them in the host environment, but you have to switch the host port to the correct forwarded port (from 3306 to 33060 for MySql).

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.

No comments: