darkghosthunter / larafind
Small utility to find PSR-4 classes from the project path.
Fund package maintenance!
Ko Fi
paypal.me/darkghosthunter
Requires
- php: ^8.0
- illuminate/container: 8.*
- illuminate/support: 8.*
- symfony/finder: 5.*
Requires (Dev)
- mockery/mockery: ^1.4
- orchestra/testbench: ^6.16
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2022-04-29 18:50:09 UTC
README
Larafind
Small utility to find PSR-4 classes from the base application path or project root.
use DarkGhostHunter\Larafind\Facades\Find; use Illuminate\Database\Eloquent\Scope; $classes = Find::path('Scopes')->implementing(Scope::class)->get();
You can use this as a way to "auto-discover" classes a developer (or you) may have under a given directory.
Requirements
- PHP 8.0
- Laravel 8.x
Installation
You can install the package via composer:
composer require darkghosthunter/larafind
Usage
Use the Find
facade to easy your development pain. The facade creates a "builder" of sorts that will return a list of all discovered PSR-4 compliant classes as a ReflectionClass
.
By default, the Finder will use the default app
directory, but you can use the path()
method to look for a specific folder in your application path.
use DarkGhostHunter\Larafind\Facades\Find; $classes = Find::path('Scopes')->get();
To look for other paths inside your project root, use the basePath()
method. Note that Finder ensures the path you're using is autoloaded.
use DarkGhostHunter\Larafind\Facades\Find; $classes = Find::basePath('app_foo/Scopes')->get();
Recursive
The discovery is recursive, meaning, it will expand into child directories. You can make it non-recursive using nonRecursive()
:
use DarkGhostHunter\Larafind\Facades\Find; $classes = Find::path('Scopes')->nonRecursive()->get();
Filtering
The Find
returns a Collection of items, so you can use the filter()
method to get only those classes that pass a truth test.
use DarkGhostHunter\Larafind\Facades\Find; $classes = Find::path('Scopes')->nonRecursive()->get() ->filter(fn($class) => str_starts_with($class->name, 'Foo'));
To make things simpler, you can use some pre-filtering methods to avoid calling a filter manually after you get the collection:
Method | Description |
---|---|
implementing() |
Filter by implementing interfaces. |
extends() |
Filter by extending class. |
uses() |
Filter by used all traits. |
methods() |
Filter by public methods. |
properties() |
Filter by public properties. |
use DarkGhostHunter\Larafind\Facades\Find; use Illuminate\Database\Eloquent\Model; $arrayAccessible = Find::implementing(ArrayAccess::class)->get(); $eloquentModels = Find::extending(Model::class)->get(); $usesTraits = Find::using('App\MyCustomTrait')->get(); $hasMethod = Find::methods('handle', 'terminate')->get(); $hasProperties = Find::properties('service', 'model')->get();
License
The MIT License (MIT). Please see License File for more information.