They Are Many

In a complex Laravel application I'm working on, I had to implement a dynamic system to integrate external and heterogeneous sources of data. So I built on the ServiceProviders feature provided by Laravel and created a ContentsDriver abstract class including the internal events handling flow and to be extended by the different effective files each implementing a source.

Now I have to dynamically create those drivers on behalf of a configuration got from the database, and the whole construction breaks down: each ContentsDriver handles a single source, I would have to register many of them, but of course I cannot autoload many times the same class.

Solution: fake new classes to load.

abstract class DummyPlug extends ContentsDriver
{
    public static function generate($identifier, $name)
    {
        $random = 'DummyPlug' . str_random(10);

        $string = <<<CLASS
use App\DriversBase\DummyPlug;

class $random extends DummyPlug {
    public function __construct()
    {
        parent::init('$identifier', '$name');
    }
}
CLASS;

        eval($string);
        App::register($random);
        return $random;
    }
}

Here, the DummyPlug (cit.) class includes a single function to actually fetch and elaborate the informations, generic enough to work for all the new dynamic drivers instantiated by configuration. I simply create new classes with random names extending this one, and register to the Laravel App to glue them with the whole flow.

Unelegant, but working.