kenshin9
kenshin9

Reputation: 2375

Putting a constant in model for each value in the database

I have a permissions table, which will eventually have up to 100 permissions. Things like "Add User", "Edit User", etc. Would it be acceptable to create a const for each permission in my Permissions model?

The reason is that I'll have a single method that will be used to check if a user has a permission, so I'd want to be able to do something like $this->hasPermission(Permission::USER_ADD) and not have to use magic numbers that would require me to it up every time.

I initially was aiming to trim down the number of records, so instead of having individual CRUD permissions for each resource, I'd just have a permissions for Users along with a corresponding column for the CRUD actions. However, it's not flexible enough for me since there are cases where a particular permission doesn't fall under those CRUD actions. For instance, "View Disabled Users".

I don't particularly see a problem with the constants, but wanted some input if this is a bad practice or the like. Thanks in advance.

Upvotes: 0

Views: 91

Answers (1)

t1gor
t1gor

Reputation: 1292

I personally don't see a problem with a 100 constants if the domain requires that. What I would probably do in this case is move the constants to the separate class, like:

<?php

abstract class Acl {
    const USER_ADD = 'USER_ADD';
    ...
}

and then check by those: $this->hasPermission(Acl::USER_ADD) This way your model will not get polluted as you grow the number of permissions.

From personal experience, there is usually no benefit from storing your permission objects in the DB with CRUD as you can add permission objects, but the new feature for it still has to live in the code. Within one of the previous projects, we stored the objects in the code and referenced those in the DB, e.g. vice versa of what you're trying to acheive.

On the other hand, it might be benefitial to check some other (community) solutions for ACL, like the following, for instance:

Upvotes: 1

Related Questions