Published Feb 18, 2019 / 2 min read
PSR-4: autoloading and namespaces
Introduction
A common convention to achieve more structure for your projects is to use 1 file for 1 class. Without require
each file over and over again, we can make use of a PSR-4 autoloader. This is a well known standard for PHP projects.
I published an example project on a GitHub repository.
PSR-4 configuration
The configuration takes place within the composer.json
file. The structure is as follows:
"autoload": {
// define autoloader standard
"psr-4": {
// define project name and point to
// your root directory of files
"Projectname\\":"src"
}
}
IMPORTANT: Do not forget to run composer dump-autoload
each time you make any chances on the configuration. Else, the chance will not take place.
Define root directory
The root directory is the base directory for all your files. The namespaces will be relative to your defined root directory. Pick as name the name of your project or company.
Require autoloader
You need to enable the autoloader at an entry point of your application. A good place would be your index.php
. Simply require
the autoloader files.
require 'vendor/autoload.php';
Use namespaces
use appropriate namespace
for your class files. Those namespaces are relative from the file directory you specified within autoloader config. In our case src
// for a file within /src
namespace Projectname;
// for a file within src/xyz
namespace Projectname\xyz
Import files
In order to use various objects within your files, make sure to import those classes with the use
keyword.
// for files within the file root
use Projectname;
// for files within other pathes
use Projectname\xyz;
Further resources
- Example autoloader integration as GitHub repository
- PSR-4 documentation
- Autoloader-Tutorial by Jeffrey Way from Laracast