Skip to content
Home » Learn PHP Namespace and Class Loader easy way

Learn PHP Namespace and Class Loader easy way

Let’s take index.php file first.

<?php

require_once __DIR__ . '/autoload.php';

use MyNamespace\Controllers\RiponController;
use MyNamespace\Controllers\MasiurController;

$riponController = new RiponController();
$masiurController = new MasiurController();

echo "<pre>";
print_r($riponController->index());
echo "</pre>";

echo "<hr>";

echo "<pre>";
print_r($riponController->serviceFunctionOfRipon());
echo "</pre>";

echo "<hr>";

echo "<pre>";
print_r($riponController->serviceFunctionOfMasiur());
echo "</pre>";


echo "<hr>";
echo $riponController->demoView();

echo "<hr>";
echo "<pre>";
print_r($masiurController->myfunction());
echo "</pre>";

Now time for the autoload.php file. This is very important file which actually loads the classes dynamically.

<?php
spl_autoload_register(function ($class) {
    $prefix = 'MyNamespace\\';
    $base_dir = __DIR__ . '/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

Let’s setup a class. The file also imports another class.

<?php

namespace MyNamespace\Controllers;
use MyNamespace\Services\MasiurService;

class RiponController
{
    private $riponService;
    public function __construct()
    {
        $this->riponService = new \MyNamespace\Services\RiponService();
    }

    public function index()
    {
        return [
            'hello' => 'world from Ripon Controller index',
            'details' => 'I am about the details of Ripon Controller. I hope you will like it.'

        ];
    }

    public function serviceFunctionOfRipon()
    {
        return $this->riponService->index();
    }
    public function serviceFunctionOfMasiur()
    {
        $masiur = new MasiurService();
        return $masiur->index();
    }

    public function demoView()
    {
        $myData = $this->riponService->index();
        return "
                <h1>Hello World</h1>
                <p>This is a demo view</p>
                <p>It is a demo view from Ripon Controller</p>
                <p style='color:red'>It is a demo view from Ripon Controller</p>
                ".date('Y-m-d H:i:s')."<br>".$myData['name']."<br>".$myData['email']."<br>".$myData['phone']
            ;
    }

}

This project actually gives an idea of how the classes can be loaded dynamically.

Full source code can be found in this Github Repo: https://github.com/masiur/PHP-Namespace-Learn

Leave a Reply

Your email address will not be published. Required fields are marked *