Rails-like Console for PHP

If you’ve ever used Ruby on Rails, you know it has an amazing console that allows you to execute code within a fully bootstrapped application environment. With the rails console command, you can gain access to your database and models in a command-line interface read-eval-print loop (REPL) for your application. This is made possible by interactive Ruby, irb. I’ve always been curious why PHP frameworks like WordPress and Magento don’t embrace a similar type of tool, even though PHP has a similar command-line interface that you can access by running php -a in your terminal.

Although php -a is similar to irb in many ways, you cannot combine php -a with the file-parsing option -f. This makes it virtually impossible to create a Rails-like console REPL for PHP frameworks like WordPress, Magento, Drupal, etc. Apparently, Facebook wrote phpsh for this very reason. But wait a second…phpsh is written in Python? That seems out of place to me.

Doing it the PHP way…

As it turns out, it has been possible to do this all along, ever since PHP 4.2.3. In 4.2.3, a php.ini directive was added called auto_prepend_file. This makes the whole thing possible!

franklin@desktop-ubuntu:~$ php -d auto_prepend_file=init.php -a
Interactive shell

php > print_r(get_defined_vars());

Further Reading

If you think this technique may be useful for you in your everyday development, check out the interactive console wrappers I’ve released for Magento and WordPress.