Weave Code
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

Php Structure Discoverer Laravel Package

spatie/php-structure-discoverer

Discover PHP classes, interfaces, traits, and enums that match conditions (e.g., implement an interface) across your project. Fast scanning with built-in caching and rich metadata—ideal for auto-registration, tooling, and framework integrations.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel Native Integration: The package is designed with Laravel in mind, offering a LaravelDiscoverCacheDriver and Artisan commands (structure-scouts:cache, structure-scouts:clear), making it a seamless fit for Laravel-based applications.
  • Modularity: The package’s focus on discovering structures (classes, interfaces, enums, traits) aligns well with Laravel’s dependency injection, service container, and reflection-heavy ecosystem (e.g., Eloquent models, service providers, middleware).
  • Cache-Driven Performance: Built-in caching (via Laravel’s cache system or file-based) ensures production performance remains optimal, reducing runtime discovery overhead.
  • Extensibility: Supports custom conditions (closures or classes) and cache drivers, allowing TPMs to tailor behavior for domain-specific needs (e.g., filtering by namespace, attributes, or inheritance chains).

Integration Feasibility

  • Low Friction: Installation is trivial (composer require), and Laravel-specific setup (config publishing, Artisan commands) is minimal.
  • Backward Compatibility: Works with PHP 8.1+ and Laravel 9+, ensuring compatibility with modern stacks.
  • No Breaking Changes: MIT license and Spatie’s track record suggest stability; the package is battle-tested in production.
  • Parallel Processing: Optional parallel scanning (via amphp/parallel) accelerates discovery in large codebases, though this adds a minor dependency.

Technical Risk

  • Reflection Overhead: While cached, initial discovery scans can be resource-intensive for monolithic applications (mitigated by parallel processing and caching).
  • Namespace/Path Dependencies: Incorrect structure_scout_directories config may miss critical classes (e.g., vendor packages). Requires careful validation during integration.
  • Cache Invalidation: Manual cache clearing (php artisan structure-scouts:clear) may be needed post-deployment if code changes affect discovery logic.
  • Custom Conditions Complexity: Advanced filtering (e.g., attribute-based or closure logic) could introduce subtle bugs if misconfigured.

Key Questions for TPM

  1. Discovery Scope:
    • Should we include vendor classes (e.g., Laravel core, third-party packages) in scans, or restrict to app/?
    • How will we handle dynamic class loading (e.g., plugins, modular packages)?
  2. Performance Trade-offs:
    • Is the parallel processing overhead justified for our codebase size?
    • Should we pre-warm caches during deployment (e.g., via CI/CD) or rely on lazy loading?
  3. Cache Strategy:
    • Which cache driver (file vs. Laravel) aligns best with our infrastructure (e.g., shared storage vs. Redis)?
    • How will we handle cache staleness in long-running processes (e.g., queues)?
  4. Use Cases:
    • Will this replace existing manual class discovery (e.g., class_uses, get_declared_classes) or augment it?
    • Are there security implications (e.g., exposing internal class structures via APIs)?
  5. Testing:
    • How will we mock/verify discovery logic in unit tests (e.g., for custom conditions)?
    • Should we benchmark discovery times against alternatives (e.g., ReflectionClass loops)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Ideal for Laravel apps leveraging:
    • Service Providers: Auto-register discovered classes (e.g., event listeners, commands).
    • Eloquent: Dynamically resolve model relationships or policies.
    • Middleware/Pipes: Filter HTTP requests based on discovered traits/attributes.
    • Testing: Generate test doubles or fixtures from discovered structures.
  • PHP-Generic Apps: Useful for non-Laravel PHP apps needing reflection utilities (e.g., CLI tools, libraries).
  • Composer Packages: Package maintainers can ship pre-configured scouts for their classes (e.g., MyPackage\Scouts\CommandsScout).

Migration Path

  1. Pilot Phase:
    • Start with non-critical discovery (e.g., logging discovered classes for debugging).
    • Use inline discovery (no scouts) to validate results:
      $models = Discover::in(app_path('Models'))->classes()->extending(Model::class)->get();
      
  2. Structured Adoption:
    • Migrate to scouts for reusable queries (e.g., PolicyScout, EventScout).
    • Replace hardcoded class lists (e.g., in config or factories) with dynamic discovery.
  3. Performance Optimization:
    • Enable parallel processing for large codebases.
    • Configure cache warming in deployment pipelines:
      php artisan structure-scouts:cache --env=production
      
  4. Deprecation:
    • Phase out legacy manual discovery logic (e.g., array_filter(get_declared_classes(), ...)).

Compatibility

  • Laravel Versions: Tested on Laravel 9+; may require adjustments for older versions (e.g., cache driver APIs).
  • PHP Versions: Requires PHP 8.1+ (for enums, attributes). Downgrade paths exist but may limit features.
  • IDE/Tooling: No known conflicts with PHPStorm, VSCode, or static analyzers (e.g., Psalm, PHPStan).
  • Database: Cache drivers (e.g., Redis) must be pre-configured in Laravel’s config/cache.php.

Sequencing

  1. Pre-Integration:
    • Audit existing class discovery logic (e.g., ReflectionClass, get_class_methods).
    • Document critical classes that must be discoverable (e.g., auth guards, custom Eloquent models).
  2. Initial Rollout:
    • Add to composer.json and publish config.
    • Implement one scout (e.g., for policies) and test in staging.
  3. Iterative Expansion:
    • Add scouts for high-value use cases (e.g., commands, middleware, events).
    • Replace manual logic incrementally (e.g., one module at a time).
  4. Post-Launch:
    • Monitor cache hit rates and adjust drivers (e.g., switch to Redis for distributed setups).
    • Add CI checks to validate discovery results (e.g., "All ShouldBeDiscoverable classes are found").

Operational Impact

Maintenance

  • Cache Management:
    • Pros: Caching reduces runtime overhead; scouts encapsulate logic.
    • Cons: Cache invalidation requires manual clearing or event-based triggers (e.g., files-changed events).
    • Best Practice: Use Laravel’s cache:clear or custom events to invalidate caches post-deploy.
  • Configuration:
    • structure_scout_directories must be updated if codebase structure changes (e.g., new modules).
    • ignored_files can grow over time (e.g., exclude test classes, generated files).
  • Dependency Updates:
    • Monitor Spatie’s releases for breaking changes (e.g., cache driver interfaces).

Support

  • Debugging:
    • Discovery failures may stem from:
      • Incorrect paths in structure_scout_directories.
      • PHP reflection limitations (e.g., anonymous classes, dynamic proxies).
      • Cache corruption (mitigated by structure-scouts:clear).
    • Tooling: Use Discover::in(__DIR__)->full()->get() to inspect raw metadata.
  • Performance Issues:
    • Slow initial scans: Enable parallel processing or adjust parallel(N).
    • High memory usage: Limit discovery scope or use chunked processing.
  • Support Channels:

Scaling

  • Horizontal Scaling:
    • Cache drivers (e.g., Redis) must support distributed setups.
    • Parallel processing is process-bound (not thread-safe in PHP); scale by distributing discovery across workers.
  • Vertical Scaling:
    • Large codebases (>10K classes) may benefit from:
      • Directory whitelisting (exclude vendor, tests).
      • Incremental discovery (scan only modified files post-deploy).
  • Microservices:
    • Deploy scouts as shared libraries or use gRPC to centralize discovery.

Failure Modes

Failure Scenario Impact Mitigation
Cache corruption Stale/incorrect discovery results Use NullDiscoverCacheDriver in tests; add health checks.
Missing directories in config Critical classes undiscovered Validate config in CI; use Discover::in()->get() to audit.
PHP reflection errors Exceptions during discovery Wrap discovery in try-catch; log errors.
Parallel processing deadlocks Slow
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope