How to run methods of all classes extending an interface on symfony

Asked

Viewed 96 times

0

I needed something similar to that console doctrine:fixtures:load in relation to class DataFixtureLoader and the interface OrderedFixtureInterface that is, I want to make a Command where it searches all the classes that extended the abstract class or interface and runs the interface method.

The problem is that I don’t know where to refer to these classes in Symfony.

How do I list all classes that extend a particular class or interface in Symfony?

1 answer

1


I will give an answer based on what the doctrine/data-fixtures-bundle makes, and you can base your system on that.

In the archive LoadDataFixturesCommand.php, which is exactly where the command resides doctrine:fixtures:load, has this block of code:

$dirOrFile = $input->getOption('fixtures');
if ($dirOrFile) {
    $paths = is_array($dirOrFile) ? $dirOrFile : array($dirOrFile);
} else {
    $paths = array();
    foreach ($this->getApplication()->getKernel()->getBundles() as $bundle) {
        $paths[] = $bundle->getPath().'/DataFixtures/ORM';
    }
}
$loader = new DataFixturesLoader($this->getContainer());
foreach ($paths as $path) {
    if (is_dir($path)) {
        $loader->loadFromDirectory($path);
    }
}

First the code checks if you specified any fixture in particular - otherwise, it scans the directories /DataFixtures/ORM of all the Bundles of your project in order to seek all the fixtures which are in them. Then the command iterates through all directories to see if they are valid and, finally, load the fixtures contained in each of them.

What you can do is something similar: set a directory pattern where the files that will be executed should reside, load them, check if each of them implements the desired interface (with the function class_implements) and execute them through the implemented method. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.