jeudi 24 septembre 2015

Does Eloquent handle caching of related entities?

I'm exploring Laravel's Eloquent as a drop-in replacement for my project's current, home-grown active record data layer. Currently, I have a class User that supports a many-to-many relationship with another class, Group. My current implementation looks something like:

class User {

    protected $_groups;  // An array of Group objects to which this User belongs

    public function __construct($properties = []){
        ...
    }

    public function groups() {
        if (isset($_groups))
            return $_groups;
        else
            return $_groups = fetchGroups();
    }

    private function fetchGroups() {
        // Lazily load the associated groups based on the `group_user` table
        ...
    }

    public function addGroup($group_id) {
        // Check that the group exists and that this User isn't already a member of the group.  If so, insert $group_id to $_groups.
        ...
    }

    public function removeGroup($group_id) {
        // Check that the User is already a member of the group.  If so, remove $group_id from $_groups.
        ...
    }

    public function fresh() {
        // Reload user and group membership from the database into this object.
        ...
    }

    public function store() {
        // Insert/update the user record in the `user` table, and insert/update/delete records in `group_user` based on the contents of `$_group_user`.
        ...
    }

    public function delete() {
        // If it exists, delete the user record from the `user` table, and delete all associated records in `group_user`.
        ...
    }
}

As you can see, my class:

  1. Performs lazy loading of related groups, caching after the first time they're queried;
  2. Maintains an internal representation of the User's relationship with their Groups, updating in the database only when store is called;
  3. Performs sanity checks when establishing relationships, making sure that a Group exists and is not already related to the User before creating a new association.

Which, if any of these things, will Eloquent automatically take care of for me? Or, is my design flawed in some way that Eloquent can solve?

You can assume that I will re-implement User as User extends Illuminate\Database\Eloquent\Model and use Eloquent's belongsToMany as a replacement for my current fetchGroups method.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire