开发者

Dynamically open php file and check if class extends abstract class (for custom module)

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 name开发者_JS百科d 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.


Not sure if you got an answer for this, but I found out that the php function is_subclass_of is an effective way of testing parent classes (or abstract classes):

http://www.php.net/manual/en/function.is-subclass-of.php


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:

if ($oFile->isFile() && preg_match('/^(.*)(?<!Abstract)\.php$/', $oFile->getFileName(), $aMatches)) {

Not ideal as I would like to test with instanceof but workable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜