Custom adjustment for controllers/models with autoload

Let’s assume an Slim-App for multiple users (with Auth), hosted on the customer server. This is the structure:

app
— controllers
---------testcontroller,php
— models
---------mymodel.php

Some of our customers need an customized version of this app, but the files should stored in a special folder (upgrade capability).

app
— controllers
---------testcontroller,php
— models
---------mymodel.php
—custom
------ controllers
------------testcontroller,php (extends controllers/testcontroller.php)
------ models
------------mymodel.phpp (extends models/mymodels.php)

Is there a way to autoscan the “custom” folder and extend the "original controllers and models.

Thank you for your help!

Alex

I would look into creating a custom autoloader that extends on the composer autoloader. Based on an example at https://github.com/composer/composer/issues/1493#issuecomment-12492276:

In your index.php:

<?php

require_once __DIR__ . '/custom_autoloader.php';

$controller = new App\Controller\MyController();
$controller();

And then in customer_autoloader.php:

<?php

class CustomLoader
{
    private $loader;

    public function __construct($loader)
    {
        $this->loader = $loader;
    }

    public function loadClass($name)
    {
        $filename = '/* construct file name of php file */';
        if (is_file($filename)) {
            require_once $filename;
            return true;
	} else {
            return $this->loader->loadClass($name);
        }
    }
}

$loader = require __DIR__ . '/vendor/autoload.php';
$loader->unregister();
spl_autoload_register(array(new CustomLoader($loader), 'loadClass'));
1 Like

Let’s assume that each customer has some of the custom work
app
— controllers
---------testcontroller,php
— models
---------mymodel.php
—custom
-----customer1
--------- controllers
---------------testcontroller,php (extends controllers/testcontroller.php)
--------- models
---------------mymodel.phpp (extends models/mymodels.php)
-----customer2
--------- controllers
---------------anothercontroller,php (extends controllers/anothercontroller.php)
--------- models
---------------mymodel.phpp (extends models/mymodels.php)

What you can do, (based on the customer) is load the correct class via reflection.
$refClass = new \ReflectionClass(‘app\custom\customer1\testcontroller’);
and go from there.
(if the class is not found, then load the normal one)

1 Like