I have an admin process that scans some directories and files to see if certain php files extend an abstract class. So I have a directory structure as follows.
/models
/models/Random.php
/models/Payment/Abstract.php
/models/Payment/Cash.php
/models/Payment/Credit.php
/models/Payment/Cheque.php
cash.php, credit.php and cheque.php extends abstract.php which are named as MyApp_Payment_Cash, MyApp_Payment_Credit, MyApp_Payment_Cheque.php and MyApp_Payment_Abstract.
I need to produce an array that is array('Cash', 'Credit', 'Cheque');. I have code as follows:
$aModules = array();
foreach (new DirectoryIterator(APPLICATION_PATH . '/models/Payment') as $oFile) {
if (preg_match('/^(.*)\.php$/', $oFile->getFileName(), $aMatches)) {
$sName = sprintf('MyApp_Payment_%s', $aMatches[1]);
if ($sName instanceof MyApp_Payment_Abstract) {
$aModules[] = $sName;
}
}
}
But that obviously doesn’t work (instanceof doesn’t work this way on strings). I tried also tried try… catch on new $sName() but PHP threw a fatal when it tried new MyApp_Payment_Abstract.
As you might gather I’m trying to build an extendable payment system that allows new payment methods to be added in the future.
I could change my regex to something like /^(?!Abstract|.*)\.php$/ but that seems a rather blunt instrument for a true test.
I could not find an effective way of dealing with this so I trusted that all the files were in the correct place and used:
Not ideal as I would like to test with
instanceofbut workable.