Search code examples
phpphpdoc

PHP Class scanner


This is maybe rather strange, but I want to make a class scanner.

Let's say, I want to make a REST route, but I am too lazy to write route for each classes. So, my folder is organized as follows:

lib
|-router.php
service
|-modulea
  |-this.php
  |-that.php
|-moduleb
  |-notthis.php
  |-notthat.php

Inside services classes, I'll put annotation like

class This {
   /**
   * @path this/@id
   */
  public function get($id) {
  }
}

Now, if I want to scan all classes inside service folder, and then call

Router->register('this/@id', 'This->get(@id)')

every time it finds a class with @path annotation

My question is, what is the best way to implement it?

  1. For scanning, I reckon that it is an expensive process. So I plan to put a scanner, and create a file, that will be rewritten when it detects a change in folder structure. But how can I detect change in folder effectively during call, invalidate cache, and rescan? I really don't want to do rescan for every N times. So I want to do a checksum and rescan only when changes detected. This data file will then be used to feed route data by Router class.

  2. For annotation, I plan to follow PHPDoc standard syntax, but what is the effective way to read @path annotation? Should I use ReflectionClass, or is it better to just get_file_contents and parse it? Since I think I won't need to instantiate the class, only to gather all information and put them in a serialized file.

Note: I am NOT looking for framework. I am looking for a way to compile a list of all controllers, and feed them to the framework.

Thank you


Solution

  • You should check out some of the existing solutions to your problems.

    Just to look at annotations, the best option I'm aware of is Doctrine Annotations

    You also might be interested in an existing routing component, such as Symfony Router - works as an independent component, including annotations for configuration, or within the Symfony framework.