Skip to main content
These utilities are designed to be standalone or used by other subsystems (like the Router) to reduce boilerplate and enable zero-config automation.

ClassLocator

The ClassLocator is a powerful utility used to scan the filesystem and identify PHP classes that belong to a specific namespace.

Purpose

Apivalk uses the ClassLocator 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 automated route discovery, 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

use apivalk\apivalk\Util\ClassLocator;

// Initialize the locator with a physical path and a base namespace
$path = __DIR__ . '/Controllers';
$namespace = 'App\\Controllers';

$locator = new ClassLocator($path, $namespace);

// Find all classes in that path matching the namespace
$classes = $locator->find();

foreach ($classes as $classInfo) {
    echo "Found Class: " . $classInfo['className'] . "\n";
    echo "File Path: " . $classInfo['path'] . "\n";
}

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 for ClassLocator in Apivalk is within the routing system to enable zero-config controller discovery: