DEV Community

pcreem
pcreem

Posted on

Write a simple PSR-4 autoload

$mkdir App
$mkdir App/Data
$code App/Data/Database.php
Enter fullscreen mode Exit fullscreen mode

App/Data/Database.php

<?php
namespace App\Data;

class Database {
    public function __construct()
    {
        echo "the init\n";
    }

    public function sayHi()
    {
        echo "create database\n";
    }
}
Enter fullscreen mode Exit fullscreen mode

$code composer.json

{
    "autoload": {
        "psr-4": {
            "App\\":"App/"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

$code index.php

<?php
require __DIR__ . '/vendor/autoload.php';
use App\Data\Database;

$obj  = new Database();

echo $obj->sayHi();
?>
Enter fullscreen mode Exit fullscreen mode

$composer dump
$php index.php

output

the init
create database
Enter fullscreen mode Exit fullscreen mode

repo: https://github.com/pcreem/psr-4Autoload

Top comments (0)