I have several classes that implement IInfoProvider
. Each subclass has a re-implemented function called providesInfoFor()
which returns a string
of the name of the type of device it can perform actions on. Each subclass provides different types of actions. For instance ABCInfoProvider
will declare functions like doThis($device)
and doThat($device)
while XYZInfoProvider
will declare functions like doNow($device)
and doLater($device)
. I have not instantiated any instances of ABCInfoProvider
or XYZInfoProvider
so they do not appear in my list of get_declared_classes
. This is a Laravel based app and below is the snippet of code I'm trying to get working:
//Works if I uncomment these two lines, which I don't want to do
//$a = new ABCDeviceInfoProvider();
//$a = new XYZDeviceInfoProvider();
//Iterate over each class
foreach (get_declared_classes() as $className) {
//Check if the class derives from IInfoProvider
if (in_array(IInfoProvider::class, class_implements($className))) {
//Create an instance of the class since it derives from IInfoProvider
$infoProvider = new $className();
//Check that the IInfoProvider has a specific function on it
if (method_exists($infoProvider, $action)) {
//Call the function, this is equivlent to 'new ABCInfoProvider()->doThis($device);'
$response = $infoProvider->$action($device);
return response()->json($response);
} else {
return response()->json(['error' => 'Action not implemented for device'], 400);
}
}
}
So, the question is, how can I get this to work if I haven't declared an instance of any of my IInfoProviders
yet? Is there another way altogether where I can at run-time call a function on a class that may or may not exist?
Aucun commentaire:
Enregistrer un commentaire