dimanche 19 avril 2020

Wrapping eloquent model to another class causes exceeded nesting

I'm using Laravel 5.5. I wrote a wrapper that takes an Eloquent model and wraps it to an Entity class and each model has own wrapper. Assume, the User has many products and a Product belongs to one user. When wrapping, I need to get products of a user and pass them to product wrapper to wrap them into the product entities. In the product wrapper, I need to get user owner of this product to wrap it to the user entity. So again, In the user wrapper, I need user products!, and this creates an infinite loop.

EntityWrapper:

abstract class EntityWrapper
{
    protected $collection;
    protected $entityClass;
    public $entity;

    public function __construct($collection)
    {
        $this->collection = $collection;
        $this->entity = $this->buildEntity();
    }

    protected function buildEntity()
    {
        $tempEntity = new $this->entityClass;

        $Entities = collect([]);

        foreach ($this->collection as $model) {
            $Entities->push($this->makeEntity($tempEntity, $model));
        }

        return $Entities;
    }

    abstract protected function makeEntity($entity, $model);
}

UserEntityWrapper:

class UserEntityWrapper extends EntityWrapper
{
    protected $entityClass = UserEntity::class;

    protected function makeEntity($userEntity, $model)
    {
        $userEntity->setId($model->user_id);
        $userEntity->setName($model->name);

        // set other properties of user entity...

        //--------------- relations -----------------
        $userEntity->setProducts((new ProductEntityWrapper($model->products))->entity);

        return $userEntity;
    }
}

UserEntity:

class UserEntity
{
    private $id;
    private $name;
    private $products;
    //... other properties

    public function setProducts($products)
    {
         $this->products = $products;
    }

    // other getters and setters...
}

ProducEntity:

class ProductEntity
{
    private $id;
    private $userId;
    private $user;
    // other properties...

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

    // other getters and setters...
}

Well, how can I prevent the nesting call to relationship between models? Thanks to any suggestion.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire