views:

33

answers:

1

How do I check an external file for a class?

I am trying to setup a install feature for my modules, so I am trying to get it to load a list of directories and then check if the module file has a method called install. So only the modules with this method will be shown in the list.

Here is my code so far:

$output .= '<div id="module-dialog" title="Add Widget"><form id="widget-list" name="widget-list">

<select name="widgets" size="12" id="widgets-list">';

            $dirHandler = opendir('modules') or die ("Could not open module folder");

            while ($dir = readdir($dirHandler)) {
                if($dir!="." && $dir!=".."){
                    // Code to filter out modules with install class -- goes here
                    $output .='<option>'.$dir.'</option>';
                }
            }


 $output .='</select></form></div>';

The module file name is the same as the directory name. example: folder:Admin, file:Admin.php

If this can not be done then I guess I will create a separate file just for the install function.

A: 

I assume you mean "How can I find out whether a PHP file defines a certain class?"

If you can include each PHP files you want to analyze

it's easy: Just compare the results of get_declared_classes() before and after the inclusion:

$before = get_declared_classes();
include "myfile.php";
$after = get_declared_classes();
$new_classes = array_diff($before, $after);
print_r($new_classes);  // Outputs all classes defined in myfile.php

If you can't include the PHP files (e.g. because they have the same class name)

This is more tricky. If you want to do it right, the tokenizer functions can analyze a file on PHP parser level. Run a token_get_all() on your file to find out which one to look for.

If your classes follow a simple convention, simply checking for "class classname" using a regular expression might be enough.

Pekka
A good suggestion, but this opens up an avenue for PHP code injection (meaning your security has gone out the window) or if you are scanning arbitarily for PHP files you could crash the interpreter by including something which does not parse.
symcbean
It's even simpler than that, you just need two module files with the same class definition for a crash. The include method works only for a limited and safe set of includes. The second method (parsing the file using a regex or token_get_all() has no such risks.
Pekka
I decided to use ini files, so each module will have an ini file with all of the install information. Thanks for the suggestion though.
WAC0020