Best Practices for Large Models at Laravel

I decided to recreate the existing site that I have in Laravel, as a means of learning how the framework works, and ran into a problem. I can't seem to get a decent explanation.

I am currently using the MVC framework I created. At the moment, I will have a “model” in which there is a lot of business logic. So, for example, in my UserModel I have all the functions that interact with the database, but I also have many other functions that are associated with the user, but do not have interaction with the database.

Can I put this code in an Eloquent model?

+4
source share
3 answers

There are several opinions, but I think it’s normal to maintain user-related logic . At least I saw exactly the same approach in really large projects, where there are a lot of bloated Controller / Model classes. Using the principle of single responsibility is a good idea, but do not be fanatical when you use it. Overengineering is evil.

+3
source

This is normal. But if the model class gets too big, sometimes I create a "manager" object to push some responsibility out of the model class. For instance:

class User extends Model
{
    protected $permissionManager;

    public function __contruct(){

        //create a Manager object (in laravel create it through App:make )
        $this->permissionManager = new PermissionManager( $this );
    }
}

class PermissionManager
{
    protected $user;

    public function __contruct(User $user){
        $this->user = $user;
    }

    public function hasAccessTo(Resource $res){
        //code
    }

    public function isManager(){
        //code
    }
}

, , , "" .

:

$user->permissionManager->hasAccessTo( $resource );

, User PermissionManager (aka factory)

- Traits. Laravel ; , , . , , , , .

+3

traits. traits . , :

  • , , app/traits/database.
  • , , app/traits/misc.

UserFunctions.php, . User .

class User extends BaseUser,UserFunctions   
+1

All Articles