ClassLocator
TheClassLocator is a powerful utility used to scan the filesystem and identify PHP classes that belong to a specific namespace.
Purpose
Apivalk uses theClassLocator primarily for automated component discovery. Instead of manually registering every controller or service, the ClassLocator can scan a directory, resolve the relative paths to PSR-4 style namespaces, and verify that the classes actually exist.
It is the engine behind the RouterFilesystemCache, allowing the framework to find all controllers in your project automatically.
Core Features
- Recursive Scanning: Navigates through subdirectories to find all PHP files.
- Namespace Resolution: Automatically maps directory structures to PHP namespaces.
- Verification: Uses
class_exists()to ensure that only valid, loadable classes are returned. - Cross-Platform Compatibility: Handles both Windows (
\) and Linux (/) path separators correctly.
Usage Example
Methods
__construct(string $path, string $namespace)
Initializes the locator.
- $path: The absolute path to the directory to scan.
- $namespace: The base namespace that corresponds to that directory.
findClasses(): array
Scans the directory and returns an array of found classes.
- Returns: An array of arrays, where each element contains:
className: The fully qualified class name.path: The absolute path to the PHP file.
Integration in Apivalk
The most common use case forClassLocator in Apivalk is within the routing system to enable zero-config controller discovery: