PHP code example of bermudaphp / reflection

1. Go to this page and download the library: Download bermudaphp/reflection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bermudaphp / reflection example snippets


use Bermuda\Reflection\Reflection;

class UserController
{
    #[Route('/api/users')]
    #[Auth('admin')]
    public function index(): Response
    {
        // method implementation
    }
}

$reflection = new ReflectionMethod(UserController::class, 'index');

// Get all attributes
$attributes = Reflection::getMetadata($reflection);

// Get specific attribute type
$routes = Reflection::getMetadata($reflection, Route::class);

// Get first attribute of specific type
$route = Reflection::getFirstMetadata($reflection, Route::class);

// Check if attribute exists
$hasAuth = Reflection::hasMetadata($reflection, Auth::class); // true

use Bermuda\Reflection\Reflection;

// Reflect different types automatically
$reflection = Reflection::reflect('MyClass');           // ReflectionClass
$reflection = Reflection::reflect($object);             // ReflectionObject  
$reflection = Reflection::reflect('function_name');     // ReflectionFunction
$reflection = Reflection::reflect([$obj, 'method']);    // ReflectionMethod
$reflection = Reflection::reflect(fn() => true);       // ReflectionFunction

use Bermuda\Reflection\Reflection;

class UserService
{
    #[Inject]
    private UserRepository $repository;
    
    #[Route('/users')]
    #[Cache(ttl: 3600)]
    public function getUsers(): array
    {
        return $this->repository->findAll();
    }
    
    #[Deprecated('Use getUsers() instead')]
    public const OLD_ENDPOINT = '/api/users';
}

$reflection = new ReflectionClass(UserService::class);

// Get ALL attributes from class and its members
$allAttributes = Reflection::getDeepMetadata($reflection);
/*
Returns:
[
    'UserService::$repository' => [Inject],
    'UserService::getUsers' => [Route, Cache],
    'UserService::OLD_ENDPOINT' => [Deprecated]
]
*/

// Get specific attribute type from anywhere in the class
$injectAttributes = Reflection::getDeepMetadata($reflection, Inject::class);
/*
Returns:
[
    'UserService::$repository' => [Inject]
]
*/

// Get first occurrence of attribute in the class
$firstRoute = Reflection::getFirstDeepMetadata($reflection, Route::class);

// Check if class has attribute anywhere
$hasInject = Reflection::hasDeepMetadata($reflection, Inject::class); // true

use Bermuda\Reflection\Reflection;

// First call creates and caches ReflectionClass
$reflection1 = Reflection::class('MyClass');

// Second call returns cached instance (faster)
$reflection2 = Reflection::class('MyClass');

// $reflection1 === $reflection2 (same object)

// Manually add custom reflector to cache
Reflection::addReflector('my-key', $customReflector);

public static function getMetadata(
    ReflectionFunctionAbstract|ReflectionClass|ReflectionParameter|ReflectionConstant $reflector,
    ?string $name = null
): ?array

$allAttributes = Reflection::getMetadata($reflection);
$routeAttributes = Reflection::getMetadata($reflection, Route::class);

public static function getFirstMetadata(
    ReflectionFunctionAbstract|ReflectionClass|ReflectionParameter|ReflectionConstant|ReflectionProperty $reflector,
    string $name
): ?object

$route = Reflection::getFirstMetadata($methodReflection, Route::class);
if ($route) {
    echo $route->path; // '/api/users'
}

public static function hasMetadata(
    ReflectionFunctionAbstract|ReflectionClass|ReflectionParameter|ReflectionConstant|ReflectionProperty $reflector,
    string $name
): bool

if (Reflection::hasMetadata($reflection, Cache::class)) {
    // Handle caching logic
}

public static function getDeepMetadata(
    ReflectionClass $reflector,
    ?string $name = null
): array

// Get all attributes from everywhere in the class
$allAttributes = Reflection::getDeepMetadata($classReflection);

// Get only Route attributes from anywhere in the class
$routes = Reflection::getDeepMetadata($classReflection, Route::class);

public static function getFirstDeepMetadata(
    ReflectionClass $reflector,
    string $name
): ?object

$firstRoute = Reflection::getFirstDeepMetadata($classReflection, Route::class);

public static function hasDeepMetadata(
    ReflectionClass $reflector,
    string $name
): bool

if (Reflection::hasDeepMetadata($classReflection, Inject::class)) {
    // Class uses dependency injection somewhere
}

public static function reflect(mixed $var): null|ReflectionFunctionAbstract|ReflectionClass|ReflectionObject

$reflection = Reflection::reflect('MyClass');        // ReflectionClass
$reflection = Reflection::reflect($instance);        // ReflectionObject
$reflection = Reflection::reflect('strlen');         // ReflectionFunction
$reflection = Reflection::reflect([$obj, 'method']); // ReflectionMethod

public static function callable(callable $callable): ReflectionFunctionAbstract

$reflection = Reflection::callable('strlen');           // ReflectionFunction
$reflection = Reflection::callable([$obj, 'method']);   // ReflectionMethod
$reflection = Reflection::callable(fn() => true);      // ReflectionFunction
$reflection = Reflection::callable('Class::method');    // ReflectionMethod

public static function object(object $object): ReflectionObject

$reflection = Reflection::object($userInstance);
echo $reflection->getName(); // 'User'

public static function class(string $class): ?ReflectionClass

$reflection = Reflection::class('User');
$reflection = Reflection::class('NonExistentClass'); // null

use Bermuda\Reflection\Reflection;

class Container
{
    public function autowire(string $className): object
    {
        $reflection = Reflection::class($className);
        
        if (!$reflection) {
            throw new Exception("Class $className not found");
        }
        
        $constructor = $reflection->getConstructor();
        if (!$constructor) {
            return new $className();
        }
        
        $dependencies = [];
        foreach ($constructor->getParameters() as $parameter) {
            $type = $parameter->getType();
            if ($type && !$type->isBuiltin()) {
                $dependencies[] = $this->autowire($type->getName());
            }
        }
        
        return new $className(...$dependencies);
    }
}

use Bermuda\Reflection\Reflection;

class RouteDiscovery
{
    public function discoverRoutes(array $controllerClasses): array
    {
        $routes = [];
        
        foreach ($controllerClasses as $className) {
            $reflection = Reflection::class($className);
            
            // Find all Route attributes in the class
            $routeAttributes = Reflection::getDeepMetadata($reflection, Route::class);
            
            foreach ($routeAttributes as $path => $attributes) {
                foreach ($attributes as $route) {
                    $routes[] = [
                        'path' => $route->path,
                        'handler' => $path,
                        'methods' => $route->methods ?? ['GET']
                    ];
                }
            }
        }
        
        return $routes;
    }
}

use Bermuda\Reflection\Reflection;

class Validator
{
    public function validate(object $entity): array
    {
        $reflection = Reflection::object($entity);
        $errors = [];
        
        foreach ($reflection->getProperties() as $property) {
            $value = $property->getValue($entity);
            
            // Check for validation attributes
            $     return $errors;
    }
}

use Bermuda\Reflection\Reflection;

class EventManager
{
    public function registerHandlers(object $listener): void
    {
        $reflection = Reflection::object($listener);
        
        foreach ($reflection->getMethods() as $method) {
            $eventHandler = Reflection::getFirstMetadata($method, EventHandler::class);
            
            if ($eventHandler) {
                $this->addEventListener(
                    $eventHandler->eventType,
                    [$listener, $method->getName()]
                );
            }
        }
    }
}