Skip to content

Conversation

@calebdw
Copy link
Contributor

@calebdw calebdw commented May 17, 2025

Hello!

This adds a new PolicedBy attribute to easily associate a policy with a model (can change the name if there's better ideas):

#[PolicedBy(PostPolicy::class)]
class Post extends Model
{
}

To improve performance and avoid having to re-guess policies on every request (they should not be changing in production) I also added a new artisan policy:cache command that also executed as part of artisan optimize (same for the *:clear variants)

Note, I added a new method, Gate::getPolicyClassFor(), so I could get the policy class without incurring a performance penalty of newing up the instances just to get the class from the instance.

Finally, I added a ->withPolicies method to the ApplicationBuilder so that users can pass other directories like:

// bootstrap/app.php
return Application::configure(basePath: dirname(__DIR__))
    ->withPolicies(new LazyCollection(
        fn () => Finder::create()
            ->directories()
            ->in([app_path(), base_path('modules')])
            ->path('Models')
    )->keys())
    // ...

Thanks!

@calebdw calebdw force-pushed the calebdw/push-tlzxlxmvumtm branch from a0b76cc to 7e50955 Compare May 17, 2025 20:18
@calebdw calebdw force-pushed the calebdw/push-tlzxlxmvumtm branch from 7e50955 to 386778c Compare May 17, 2025 20:24
@calebdw calebdw force-pushed the calebdw/push-tlzxlxmvumtm branch from 386778c to 80be2b9 Compare May 17, 2025 20:35
@taylorotwell
Copy link
Member

I might call it something like UsePolicy to match UseFactory.

@taylorotwell
Copy link
Member

I don't really love the amount of code added plus a new cache command just to unlock attribute customization of policies. Policies can already be auto-discovered (even outside of app directory style applications) by just following a pretty basic convention.

@calebdw
Copy link
Contributor Author

calebdw commented May 28, 2025

@taylorotwell, I combined two ideas into one when I should have split them out

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants