mercredi 6 janvier 2016

Loading All Eloquent Models into a DI Container

So i realize that this is possibly the worst idea I've ever had, but I'm incredibly curious as to whether or not it fits into an Anti-Pattern and should be avoided, or is a perfectly acceptable solution.

In my test case I'll be using Eloquent and Pimple, however i do not believe they are relevant, as long as you have a DI Container and a ORM which uses a Model-like class. I'm also using PSR 4 Naming to make assumptions about the file structure.

The primary objective of this exercise is to automatically add all Models to your DI Container, without actually including and creating an instance of the class, so that you can be lazy and not manually define it in your DI Container.

The example code that i'm providing below skips some fine tooth checking such as ensuring that there is a parameter-less constructor, ensuring it's not already defined in the container, etc, etc

$container = new Container(); // DI Container
$directory = new RecursiveDirectoryIterator("/path/to/models");
$iterator = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $class) {
    if ($class->isFile() && $class->getExtensions() == "php") {
        $filename = $class->getBasename(".php");
        $container[$filename] = function() use ($class, $filename) {
            $classname = "\\Fully\\Qualified\\Namespace\\{$filename}";
            require_once $class;
            return new $classname();
        }        
    }
}

So the real question here essentially is, is there any Anti-Patterns in the above code, and are there any real security issues to worry about using it in practice if there isn't an Anti-Pattern that this fits into.

Aucun commentaire:

Enregistrer un commentaire