This is a simple guide to getting Composer to work with WordPress.
You will need to ensure your web server (development and production) are both running PHP 5.3.* minimum and will require the cURL extension to be enabled.
I develop and run all of my sites on a *nix environment (CentOS / Apache2 / PHP 5.4.*), so further instructions will only be valid for this platform. If you run on a Windows environment, please follow the instructions on Composer’s site.
Open up a terminal window (SSH/directly on the machine) and run the following in your home directory.
curl -s https://getcomposer.org/installer | php
We want to run composer globally, so next we will move it into your environment’s path.
sudo mv composer.phar /usr/local/bin/composer
Setting up Composer for WordPress
First navigate to your document root for your WordPress install.
Add a new file to the document root called composer.json.
Open the file in your favourite editor (in this case, vi)
In this article, I’ll provide an example of dependencies I have added to one of my recent projects which uses Doctrine2, Silex, Twig and a number of other libraries.
Save the file, and now we’re ready to download our dependencies. Run the following:
<Esc> :wq <Enter>
This process will download the libraries/framework to a new folder called ‘vendor’ in your document root. In addition to this, Composer will generate an autoloader for you to automatically include the files when they are called. The file is PSR-0 compliant and will load files by their namespace and class name.
To use the generated autoloader, open up your wp-config.php file in an editor and add the following:
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
/** Composer Autoloader */
Save the config file.
Now you should be able to use any of the libraries with a simple call to the class name in your plugins, themes, etc, eg.
$silex = new \Silex\Application();
Posted in: PHP