Yet another example of autoloading classes in a Php environment following the PSR-4 standards introduced by the Php Interopt group.
- The composer autoloader
The packagist manager (composer) features an autoloader to let us use any package libraries more easily and it let us load our own Php Objects if you tell it to.
The whole example is available on GitHub.
It features the following details :
- MC pattern (Model Controller – no View needed)
- Hierarchical structure with namespaces
- Very simple example with 2 classes
- Php 7+ strict type mode
- Typed properties
Pre-requesites
You should be running a Php server, no SQL needed. You could take a look at the Lamp & Docker guide to get a full set up running on your machine.
Composer must also be installed.
Autoloading with Composer
Let’s start by adding a composer.json configuration file :
{
"autoload" : {
"psr-4" : {
"App\\" : "src/"
}
}
}
Now issue the following command to load all the necessary packages and configure the autoloading :
$ composer dump-autoload
<?php
require __DIR__ . "/vendor/autoload.php";
use App\Controller\Frontend;
$controller = new Frontend();
$controller->home();
We only need to load the vendor/autoload php script so we can auto load our unique Frontend controller to be able to call the home() method.
The dependency is automatically added when we instantiate the controller.
Following are the Controller and Entity objects :
<?php
declare(strict_types = 1);
namespace App\Controller;
use App\Model\Entity\Person;
class Frontend
{
private Person $person;
public function __construct()
{
$this->person = new Person("Owner", 70);
}
public function home(): void
{
$this->person->sayHello();
}
}
Save the above under src/Controller/Frontend.php file.
<?php
declare(strict_types = 1);
namespace App\Model\Entity;
class Person
{
private string $name;
private int $age;
public function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
public function sayHello(): void
{
echo "Hello ".$this->name . ", I'm ".$this->age;
}
}
And the above content within src/Model/Entity/Person.php file.
Result of autoloading
Once disposed onto your server, access the webpage and appreciate the result :

That was easy, I hope that you have successfully integrated this example.
Do not hesitate to drop a comment !
[…] the example on the autoloader tutorial, we prepared a composer.json file to target our application sources files […]