PHPackages                             spatie/laravel-auto-discoverer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. spatie/laravel-auto-discoverer

ActiveLibrary

spatie/laravel-auto-discoverer
==============================

Automatically discover structures within your PHP application

2.4.0(2mo ago)178573↑130.8%17MITPHPPHP ^8.3CI passing

Since Jul 15Pushed 2mo ago4 watchersCompare

[ Source](https://github.com/spatie/php-structure-discoverer)[ Packagist](https://packagist.org/packages/spatie/laravel-auto-discoverer)[ Docs](https://github.com/spatie/php-structure-discoverer)[ GitHub Sponsors](https://github.com/LaravelAutoDiscoverer)[ RSS](/packages/spatie-laravel-auto-discoverer/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (13)Versions (28)Used By (0)

Automatically discover classes, interfaces, enums, and traits within your PHP application
=========================================================================================

[](#automatically-discover-classes-interfaces-enums-and-traits-within-your-php-application)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1d1edf8d60dd492d93a867bbf092b961ac41324746e674d07601d0113d976353/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f7068702d7374727563747572652d646973636f76657265722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/php-structure-discoverer)[![run-tests](https://github.com/spatie/php-structure-discoverer/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/run-tests.yml)[![PHPStan](https://github.com/spatie/php-structure-discoverer/actions/workflows/phpstan.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/phpstan.yml)[![Check & fix styling](https://github.com/spatie/php-structure-discoverer/actions/workflows/php-cs-fixer.yml/badge.svg)](https://github.com/spatie/php-structure-discoverer/actions/workflows/php-cs-fixer.yml)[![Total Downloads](https://camo.githubusercontent.com/4f31dbb89f3efc6f625c9533bcc0f1a2ee8f93d825fde33f4d57de6bdc1091b0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f7068702d7374727563747572652d646973636f76657265722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/php-structure-discoverer)

With this package, you'll be able to discover structures in your PHP application that fulfill certain conditions quickly. For example, you could search for classes implementing an interface:

```
use Spatie\StructureDiscoverer\Discover;

// PostModel::class, Collection::class, ...
Discover::in(__DIR__)->classes()->implementing(Arrayable::class)->get();
```

As an added benefit, it has a built-in cache functionality that makes the whole process fast in production.

The package is not only limited to classes but can also find enums, interfaces, and traits and has extra metadata for each structure.

Support us
----------

[](#support-us)

[![](https://camo.githubusercontent.com/9209b6a951687451bd3ad05e82d78f0bfe8acb7923aac718facb9603dee56cab/68747470733a2f2f6769746875622d6164732e73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f7068702d7374727563747572652d646973636f76657265722e6a70673f743d31)](https://spatie.be/github-ad-click/php-structure-discoverer)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require spatie/php-structure-discoverer
```

If you're using Laravel, then you can also publish the config file with the following command:

```
php artisan vendor:publish --tag="structure-discoverer-config"
```

This is the contents of the published config file:

```
return [
    /*
     *  A list of files that should be ignored during the discovering process.
     */
    'ignored_files' => [

    ],

    /**
     * The directories where the package should search for structure scouts
     */
    'structure_scout_directories' => [
        app_path(),
    ],

    /*
     *  Configure the cache driver for discoverers
     */
    'cache' => [
        'driver' => \Spatie\StructureDiscoverer\Cache\LaravelDiscoverCacheDriver::class,
        'store' => null,
    ]
];
```

Usage
-----

[](#usage)

You always need to define in which directories you want to look for structures:

```
Discover::in(__DIR__)->...
```

It is possible to look in multiple directories like this:

```
Discover::in(app_path('models'), app_path('enums'))->...
```

You can get the structures as such:

```
Discover::in(__DIR__)->get();
```

Which will return an array of class FCQN, and because no conditions were added, the package will return all classes, enums, interfaces, and traits.

You only discover classes like this:

```
Discover::in(__DIR__)->classes()->get();
```

Interfaces like this:

```
Discover::in(__DIR__)->interfaces()->get();
```

Enums like this:

```
Discover::in(__DIR__)->enums()->get();
```

And traits like this:

```
Discover::in(__DIR__)->traits()->get();
```

When you want to include a specific named structure, you can do the following:

```
Discover::in(__DIR__)->named('MyAwesomeClass')->get();
```

You can discover classes extending another class as such:

```
Discover::in(__DIR__)->extending(Model::class)->get();
```

Discovering classes, interfaces, or enums implementing an interface can be done like this:

```
Discover::in(__DIR__)->implementing(Arrayable::class)->get();
```

Be aware that although interfaces extend another interface, in this context, the implements keyword seemed a more logical choice to find interfaces extended by another interface. Using the `extends` method for such a filter won't work!

Classes, interfaces, or traits using an attribute can be discovered as such:

```
Discover::in(__DIR__)->withAttribute(Cast::class)->get();
```

For more fine-grained control, you can use a closure that receives a `DiscoveredStructure` object (more on that later) and should return `true` if the structure should be included:

```
Discover::in(__DIR__)
   ->custom(fn(DiscoveredStructure $structure) => $structure->namespace === 'App')
   ->get()
```

More complex custom conditions can be embedded in a class:

```
class AppDiscoverCondition extends DiscoverCondition
{
    public function satisfies(DiscoveredStructure $discoveredData): bool
    {
        return $structure->namespace === 'App';
    }
};
```

This condition can now be used like this:

```
Discover::in(__DIR__)
   ->custom(new AppDiscoverCondition())
   ->get()
```

### Combining conditions

[](#combining-conditions)

By default, all conditions will work like an AND operation, so in this case:

```
Discover::in(__DIR__)->classes()->implementing(Arrayable::class)->get();
```

The package will only look for structures that are a class **and** implement `Arrayble`.

You can create an OR combination of conditions like this:

```
Discover::in(__DIR__)
    ->any(
        ConditionBuilder::create()->classes(),
        ConditionBuilder::create()->enums()
    )
    ->get();
```

Now, the package will only discover classes **or** enum structures.

You can also create more complex operations like an or of and's:

```
Discover::in(__DIR__)
    ->any(
        ConditionBuilder::create()->exact(
            ConditionBuilder::create()->classes(),
            ConditionBuilder::create()->implementing(Arrayble::class),
        ),
        ConditionBuilder::create()->exact(
            ConditionBuilder::create()->enums(),
            ConditionBuilder::create()->implementing(Stringable::class),
        )
    )
    ->get();
```

This example can be written shorter like this:

```
Discover::in(__DIR__)
    ->any(
        ConditionBuilder::create()->exact(
            ConditionBuilder::create()->classes()->implementing(Arrayble::class),
        ),
        ConditionBuilder::create()->exact(
            ConditionBuilder::create()->enums()->implementing(Stringable::class),
        )
    )
    ->get();
```

### Sorting

[](#sorting)

By default, the discovered structures will be sorted according to the OS' default.

You can change the sorting like this:

```
use Spatie\StructureDiscoverer\Enums\Sort;

Discover::in(__DIR__)->sortBy(Sort::Name)->get();
```

Here are all the available sorting options:

```
use Spatie\StructureDiscoverer\Enums\Sort;

Discover::in(__DIR__)->sortBy(Sort::Name);
Discover::in(__DIR__)->sortBy(Sort::Size);
Discover::in(__DIR__)->sortBy(Sort::Type);
Discover::in(__DIR__)->sortBy(Sort::Extension);
Discover::in(__DIR__)->sortBy(Sort::ChangedTime);
Discover::in(__DIR__)->sortBy(Sort::ModifiedTime);
Discover::in(__DIR__)->sortBy(Sort::AccessedTime);
Discover::in(__DIR__)->sortBy(Sort::CaseInsensitiveName);
```

### Caching

[](#caching)

This package can cache all discovered structures, so no performance-heavy operations are required in production.

The fastest way to start caching is by creating a structure scout, which is a class that describes what you want to discover:

```
class EnumsStructureScout extends StructureScout
{
    protected function definition(): Discover|DiscoverConditionFactory
    {
        return Discover::in(__DIR__)->enums();
    }

    public function cacheDriver(): DiscoverCacheDriver
    {
        return new FileDiscoverCacheDriver('/path/to/temp/directory');
    }
}
```

Each structure scout extends from `StructureScout` and should have

- a definition where you describe what to discover and where. Just like we did inline earlier
- a driver to be used for the cache. When you're using Laravel, this method is not required since it is already defined in the config file

Within your application, you can use the discoverer as such:

```
EnumsStructureScout::create()->get();
```

The first time this method is called, the whole discovery process will run taking a bit more time. The second call will skip the discovery process and use the cached version, making a call to this method amazingly fast!

#### In production

[](#in-production)

When you're deploying to production, you can warm all your structure scout caches as such:

```
StructureScoutManager::cache([__DIR__]);
```

You should provide a directory where the structure scouts are stored.

If you're using Laravel, you can run the following command:``

```
php artisan structure-scouts:cache
```

It is also possible to clear all caches for structure scouts as such:

```
StructureScoutManager::clear([__DIR__]);
```

Or, if you're using Laravel:

```
php artisan structure-scouts:clear
```

##### For packages

[](#for-packages)

Since an individual user defines the directories where structure scouts can be found, packages can't ensure their structure scouts will be discovered with the cache commands.

It is possible to add structure scouts like this manually:

```
StructureScoutManager::add(SettingsStructureScout::class);
```

In a Laravel application, you typically do this within the package ServiceProvider.

#### Cache drivers

[](#cache-drivers)

##### File

[](#file)

The `FileDiscoverCacheDriver` allows you to cache discovered structures in a file. You should provide a `directory` parameter where all the cache files should be stored.

##### Laravel

[](#laravel)

The `LaravelDiscoverCacheDriver` will use the default Laravel cache. You can provide an optional `store` parameter to define the store to be used and an optional `prefix` parameter for the cache key.

##### Null

[](#null)

The `NullDiscoverCacheDriver` will not cache anything and can be used for testing purposes.

##### Your own

[](#your-own)

A cache driver can be built by extending the `DiscoverCacheDriver` interface:

```
interface DiscoverCacheDriver
{
    public function has(string $id): bool;

    public function get(string $id): array;

    public function put(string $id, array $discovered): void;

    public function forget(string $id): void;
}
```

#### Without structure scouts

[](#without-structure-scouts)

You can also use caching inline without the use of scouts, be aware warming up these caches in production is not possible:

```
Discover::in(__DIR__)
   ->withCache(
      'Some identifier',
      new FileDiscoverCacheDriver('/path/to/temp/directory')
   )
    ->get();
```

### Parallel

[](#parallel)

Getting all structures in a bigger application can be slow due to many files being scanned.

Before running in parallel, make sure to install `amphp/parallel`

```
composer require amphp/parallel
```

The process can be sped up by parallelized scanning. You can enable this as such:

```
Discover::in(__DIR__)->parallel()->get();
```

It is possible to set the number of files each process will scan:

```
Discover::in(__DIR__)->parallel(100)->get();
```

By default, each process will scan 50 files.

### Chains

[](#chains)

Often structures inherit other structures with extends and implementations. The package automatically includes these structures when discovering them. So for example

```
class Request
{
}

class FormRequest extends Request
{
}

class UserFormRequest extends FormRequest
{
}
```

When using:

```
Discover::in(__DIR__)->extending(Request::class)->get();
```

Both `FormRequest` and `UserFormRequest` will be found, and although `UserFormRequest` is not a direct descendant of `Request`, it is one through `FormRequest`.

You can disable this behavior for extending as such:

```
Discover::in(__DIR__)->extendingWithoutChain(Request::class)
```

Or for implementing as such:

```
Discover::in(__DIR__)->implementingWithoutChain(Request::class)
```

Resolving chains is a complicated and resource-heavy process. It can be completely disabled as such:

```
Discover::in(__DIR__)->withoutChains()->extending(Request::class)->get();
```

### Full information

[](#full-information)

The output will be a reference string to the structure when discovering structures. Internally the package keeps track of a lot more information which can be helpful for all purposes. You can also retrieve this information as such:

```
Discover::in(__DIR__)->full()->get();
```

Instead of returning an array of strings, now an array of `DiscoveredStructure` objects is returned. Let's go through the different types:

#### DiscoveredClass

[](#discoveredclass)

Represents a class, the `$extends` and `$implements` properties address the direct extend and implements of the class. The `$extendsChain` and `$implementsChain` properties contain all extends and implements for the complete inheritance chain.

```
class DiscoveredClass extends DiscoveredStructure
{
    public function __construct(
        string $name,
        string $file,
        string $namespace,
        public bool $isFinal,
        public bool $isAbstract,
        public bool $isReadonly,
        public ?string $extends,
        public array $implements,
        public array $attributes,
        public ?array $extendsChain = null,
        public ?array $implementsChain = null,
    ) {
    }
}
```

#### DiscoveredInterface

[](#discoveredinterface)

Represents a class, the `$extends` property addresses the direct extends of the interface. The `$extendsChain` property contains all extends for the whole inheritance chain.

```
class DiscoveredInterface extends DiscoveredStructure
{
    public function __construct(
        string $name,
        string $file,
        string $namespace,
        public array $extends,
        public array $attributes,
        public ?array $extendsChain = null,
    ) {
    }
```

#### DiscoveredEnum

[](#discoveredenum)

Represents an enum, the `$implements` property addresses the direct extends of the enum. The `$implementsChain` property contains all implements for the full inheritance chain. The `$type` property is an enum describing the type: `Unit`, `String`, and `Int`.

```
class DiscoveredEnum extends DiscoveredStructure
{
    public function __construct(
        public string $name,
        public string $namespace,
        public string $file,
        public DiscoveredEnumType $type,
        public array $implements,
        public array $attributes,
        public ?array $implementsChain = null,
    ) {
    }
}
```

### DiscoveredTrait

[](#discoveredtrait)

Represents a discovered trait within the application.

```
class DiscoveredTrait extends DiscoveredStructure
{
    public function __construct(
        public string $name,
        public string $namespace,
        public string $file,
    ) {
    }
}
```

### Parsers

[](#parsers)

The parser is responsible for parsing a file and returning a list of structures. The package comes with two parsers out of the box:

- `PhpTokenStructureParser`: Reads a PHP file, tokenizes it, and parses the tokens into structures.
- `ReflectionStructureParser`: Uses the PHP reflection API to read a file and parse it into structures.

By default, the `PhpTokenStructureParser` is used due to it being more robust, the `ReflectionStructureParser` is quite a bit faster but can completely fail the PHP process.

You can enable the `ReflectionStructureParser` as such:

```
Discover::in(__DIR__)
   ->useReflection(
      basePath: '/path/to/project/root',
      rootNamespace: null
   )
   ->get();
```

You'll likely need to set the basePath to the root of your project, and optionally the root namespace of your project which will be prepended.

For default Laravel projects this would be:

```
Discover::in(__DIR__)
   ->useReflection(basePath: base_path())
   ->get();
```

### Help? My structure cannot be found!

[](#help-my-structure-cannot-be-found)

The internals of this package will scan all files within a directory and try to make a virtual map linking all structures with their extends, uses, and implementations.

Due to this file scanning, this map is incomplete if referenced structures are not being scanned.

For example, we scan for all classes extending Laravel's `Model` in our app directory, a lot of models have been found, but the `User` model is missing.

The reason why this is happening is that:

- The package searches in the app directory for classes extending `Model`
- `User` extends `Authenticatable`, which itself extends `Model`
- `Authenticatable` is stored within the `vendor/laravel/...` directory, which isn't being scanned
- The package does not know that `Authenticatable` extends `Model`
- `User` will not be found

A solution to this problem is to include the `laravel` directory in the scanning process.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Ruben Van Assche](https://github.com/rubenvanassche)
- [Construct Finder](https://github.com/thephpleague/construct-finder) a big influence for this package
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance84

Actively maintained with recent releases

Popularity34

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 56.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~52 days

Recently: every ~101 days

Total

26

Last Release

81d ago

Major Versions

0.0.6 → 1.0.02023-02-10

v1.x-dev → v2.x-dev2023-12-21

PHP version history (3 changes)0.0.1PHP ^8.0

0.0.3PHP ^8.1

2.3.3PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7535935?v=4)[Spatie](/maintainers/spatie)[@spatie](https://github.com/spatie)

---

Top Contributors

[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (114 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (50 commits)")[![stevebauman](https://avatars.githubusercontent.com/u/6421846?v=4)](https://github.com/stevebauman "stevebauman (14 commits)")[![riasvdv](https://avatars.githubusercontent.com/u/3626559?v=4)](https://github.com/riasvdv "riasvdv (5 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (3 commits)")[![LordSimal](https://avatars.githubusercontent.com/u/9105243?v=4)](https://github.com/LordSimal "LordSimal (2 commits)")[![thecaliskan](https://avatars.githubusercontent.com/u/13554944?v=4)](https://github.com/thecaliskan "thecaliskan (2 commits)")[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (2 commits)")[![francoism90](https://avatars.githubusercontent.com/u/5028905?v=4)](https://github.com/francoism90 "francoism90 (2 commits)")[![jameswagoner](https://avatars.githubusercontent.com/u/3052854?v=4)](https://github.com/jameswagoner "jameswagoner (2 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (2 commits)")[![SebKay](https://avatars.githubusercontent.com/u/1873695?v=4)](https://github.com/SebKay "SebKay (2 commits)")[![flowl](https://avatars.githubusercontent.com/u/4543262?v=4)](https://github.com/flowl "flowl (1 commits)")[![PerryvanderMeer](https://avatars.githubusercontent.com/u/11609290?v=4)](https://github.com/PerryvanderMeer "PerryvanderMeer (1 commits)")[![ryangjchandler](https://avatars.githubusercontent.com/u/41837763?v=4)](https://github.com/ryangjchandler "ryangjchandler (1 commits)")

---

Tags

discoverlaravelphpphplaraveldiscoverphp-structure-discoverer

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/spatie-laravel-auto-discoverer/health.svg)

```
[![Health](https://phpackages.com/badges/spatie-laravel-auto-discoverer/health.svg)](https://phpackages.com/packages/spatie-laravel-auto-discoverer)
```

###  Alternatives

[spatie/php-structure-discoverer

Automatically discover structures within your PHP application

17824.5M57](/packages/spatie-php-structure-discoverer)[laravel-zero/framework

The Laravel Zero Framework.

3371.4M369](/packages/laravel-zero-framework)[pestphp/pest-plugin-drift

The Pest Drift Plugin

734.0M74](/packages/pestphp-pest-plugin-drift)[laragear/preload

Effortlessly make a Preload script for your Laravel application.

119363.5k](/packages/laragear-preload)[tapp/filament-google-autocomplete-field

Filament plugin that provides a Google Autocomplete field

3098.1k](/packages/tapp-filament-google-autocomplete-field)[elegantly/laravel-translator

All on one translations management for Laravel

6216.9k](/packages/elegantly-laravel-translator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
