Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Reflection Helper Laravel Package

cetria/reflection-helper

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require cetria/reflection-helper
    

    No service provider or package registration is required—it’s a standalone utility.

  2. First Use Case Quickly inspect a class’s properties/methods without manual reflection boilerplate:

    use Cetria\ReflectionHelper\ReflectionHelper;
    
    $reflection = ReflectionHelper::getClass('App\Models\User');
    $properties = $reflection->getProperties(); // Returns array of property names
    $methods    = $reflection->getMethods();    // Returns array of method names
    
  3. Key Entry Points

    • ReflectionHelper::getClass(string $className): Wraps new ReflectionClass() with convenience methods.
    • ReflectionHelper::getMethod(string $className, string $methodName): Wraps new ReflectionMethod().
    • ReflectionHelper::getProperty(string $className, string $propertyName): Wraps new ReflectionProperty().

Implementation Patterns

Common Workflows

  1. Dynamic Property/Method Introspection Useful for:

    • Dynamic Form Generation: Auto-detect model fields for Laravel Form requests.
      $fields = ReflectionHelper::getClass(User::class)->getProperties();
      // Generate Form fields dynamically
      
    • API Response Filtering: Whitelist/blacklist properties based on reflection.
      $allowed = ['id', 'name'];
      $filtered = collect($user)->only(
          ReflectionHelper::getClass(User::class)
              ->getProperties()
              ->filter(fn($prop) => in_array($prop, $allowed))
      );
      
  2. Dependency Injection & Service Containers Resolve constructor arguments dynamically:

    $reflection = ReflectionHelper::getClass(MyService::class);
    $params     = $reflection->getConstructorParameters();
    $container  = app();
    $service    = new MyService(...array_map(fn($param) => $container->make($param), $params));
    
  3. Laravel-Specific Integrations

    • Model Observers: Detect protected properties to trigger events.
      $reflection = ReflectionHelper::getClass(User::class);
      $protected  = $reflection->getProtectedProperties();
      // Observe changes to $protected fields
      
    • Policy/Authorization: Check method existence dynamically.
      if (ReflectionHelper::getMethod(PostPolicy::class, 'update')->exists()) {
          $this->authorize('update', $post);
      }
      
  4. Testing & Mocking Verify method/property existence in unit tests:

    public function testUserHasEmailProperty()
    {
        $this->assertTrue(
            ReflectionHelper::getProperty(User::class, 'email')->exists()
        );
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Reflection is slow. Cache results for repeated calls:
      $cachedReflection = Cache::remember("reflection_{$className}", now()->addHours(1), fn() =>
          ReflectionHelper::getClass($className)
      );
      
    • Avoid in hot paths (e.g., loop iterations).
  2. Private/Protected Access

    • By default, ReflectionHelper respects visibility. Force access with:
      $property = ReflectionHelper::getProperty(User::class, 'hiddenField');
      $property->setAccessible(true);
      $value = $property->get($user);
      
    • Warning: Breaks encapsulation; use sparingly.
  3. Dynamic Class Loading

    • If the class isn’t autoloaded (e.g., generated classes), use:
      ReflectionHelper::getClass($className, true); // $forceLoad = true
      
  4. Laravel Facade Collisions

    • The package has no facades, but if you extend it, avoid naming conflicts with Laravel’s Reflection helpers.

Tips

  1. Chaining Methods Leverage fluent interfaces for cleaner code:

    $methods = ReflectionHelper::getClass(User::class)
        ->getMethods()
        ->filter(fn($method) => str_starts_with($method, 'set'))
        ->toArray();
    
  2. Type Hints & IDE Support

    • The package returns ReflectionClass/ReflectionMethod objects under the hood. Cast to arrays or use native reflection methods:
      $method = ReflectionHelper::getMethod(User::class, 'fill');
      $params = $method->getParameters(); // Native ReflectionParameterList
      
  3. Extending Functionality

    • Override default behavior by extending the helper:
      class CustomReflectionHelper extends ReflectionHelper {
          public static function getClass(string $className, bool $includeTraits = true) {
              $reflection = parent::getClass($className);
              if ($includeTraits) {
                  $reflection->getTraits(); // Custom logic
              }
              return $reflection;
          }
      }
      
  4. Debugging

    • Dump reflection data for debugging:
      dd(
          ReflectionHelper::getClass(User::class)
              ->getProperties()
              ->mapWithKeys(fn($prop) => [$prop => ReflectionHelper::getProperty(User::class, $prop)->getType()])
      );
      
  5. Laravel Artisan Commands Use reflection to validate command arguments dynamically:

    protected function getArguments()
    {
        $reflection = ReflectionHelper::getClass($this);
        return $reflection->getConstructorParameters();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style