Я использую Laravel 5.5. Я написал оболочку, которая берет модель Eloquent и переносит ее в класс Entity
, и у каждой модели есть собственная оболочка. Предположим, у пользователя много продуктов, а продукт принадлежит одному пользователю. При упаковке мне нужно получить продукты пользователя и передать их в оболочку продукта, чтобы обернуть их в сущности продукта. В оболочке продукта мне нужно, чтобы пользователь-владелец этого продукта связал его с сущностью пользователя. Итак, еще раз, в пользовательской оболочке мне нужны продукты пользователя !, и это создает бесконечное l oop.
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;
}
}
ProductEntityWrapper:
class ProductEntityWrapper extends EntityWrapper
{
protected $entityClass = ProductEntity::class;
protected function makeEntity($productEntity, $model)
{
$productEntity->setId($model->product_id);
$productEntity->setName($model->name);
// set other properties of product entity...
//--------------- relations -----------------
$productEntity->setUser((new UserEntityWrapper($model->user))->entity);
return $productEntity;
}
}
UserEntity:
class UserEntity
{
private $id;
private $name;
private $products;
//... other properties
public function setProducts($products)
{
$this->products = $products;
}
// other getters and setters...
}
Когда я Чтобы получить пользовательские сущности путем вызова (new UserEntityWrapper(User::all()))->entity
, это вызывает бесконечное l oop. Итак, как я могу предотвратить вложенный вызов отношений между моделями? Спасибо за любое предложение.