Autoloading PHP Files with Composer (psr-4)

If you’re not sure what composer is, it’s a dependency manager for PHP. It’s very similar to NPM. Composer is a nice way to install PHP packages, manage dependencies, use it as an autoloader, etc.

Autoloading with Composer

I remember back when autoloading files in PHP was a pain. I built websites that were a horrible mess of “require” statements. The good ‘ole foolish days! There was such a thing called sql_autoload, however, I thought this was a awkward process to autoload classes without require statements.

Composer to the rescue! I discovered this amazing tool a couple of years ago and I’ve never looked back. It’s been quite useful. After all, it is the industry standard dependency manager for PHP.

Here’s how you autoload set up the autoloader. Let’s say you started a project like so:

 src -|
  ----|
  ----| 
       // yo source files
 composer.json - 
 index.php -

The “src” directory is where you want to keep all of your project files and classes (let’s say). You’ll need to add this to your composer.json file:

"autoload": {
    "psr-4": {"Company\\": "src/"}
 }

Once you’ve added that in, you’ll need to run the composer dump-autoload command to re-generate the autoloader so that PHP can recognize the files. You can read more details about this process here: https://getcomposer.org/doc/01-basic-usage.md#autoloading

Now you can import your namespace and files within your project. Let’s say you want to use a class or method withim that index.php file:

<?php
namespace Company;
require 'vendor/autoload.php';

$example = new Example();
$example->someMethod();

require ‘vendor/autoload.php’ loads up the autoloader. namespace Company loads up the “Company” namespace so that you can use the classes within your “src/” directory.

What is psr-4?

Psr-4 is a specification for autoloading classes in PHP. It’s better explained over in the documentation on PHP-Fig: http://www.php-fig.org/psr/psr-4/

Cheers!

Tyler Souza

Tyler is a very passionate full-stack developer who thrives on a challenge. He specializes in programming (mainly in Python), REST API development, and keeps up with the latest front-end technologies. When not coding, he loves to eat ramen, BBQ, and travel.

You may also like...