Gareth Redfern developer, cyclist & coffee lover

Autoloading Classes In PHP

Posted by Gareth Redfern
Category: php

Using Composer gives us autoloading for free, if you review the basic usage documentation you will see that all we need to do to use all the composer installed packages in the vendor director is add one line of code to our main file index.php:

require 'vendor/autoload.php';

With that one line of code everything we have in our vendor directory is available to use in the index.php file. If you have been following along from the previous post (Basic Composer Usage) you should have installed Monolog via Composer. From the Composer example we can now use Monolog in our index.php file by adding the following:

$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING));


Running through the above code we first create a new Monolog\Logger instance to the object variable $log. On the next line, using the object operator -> we call a method which has an object instantiated inside of it called StreamHandler from Monolog. The StreamHandler has two arguments, the first is what file you are planning to write to (app.log). The second is the log level that you would like to use (Monolog\Logger::WARNING). Finally on the last line we call the addWarning method on the log object, passing in the string Foo. If you reload the index.php file it will record the string of Foo in an app.log file at the route of the project.

Hopefully this simple example shows how easy it is to use Composer to add autoloading to your PHP app, next we will want to look at how namespacing works.