H
H
homedistiller2017-11-04 15:48:33
PHP
homedistiller, 2017-11-04 15:48:33

Which design pattern is best for loading related entities?

Not tied to any framework.
For example, there is an order entity, it contains product identifiers, a customer identifier, etc. How to implement all this beautifully and correctly using modern approaches?
Here is an example code:

class OrderEntity
{
  protected $id = 0;
  protected $member_id = 0;
  // массив идентифкаторов
  protected $items_ids = [];
}

class ItemEntity
{
  protected $id = 0;
  protected $name = '';
}

class MemberEntity
{
  protected $id = 0;
  protected $name = '';
}

class OrderService
{
  public function getOrder($id): OrderEntity
  {
    return $this->mapper->getOrder($id);
  }
}

$service = new OrderService();
$order = $service->getOrder(1);

There is an order. And now it's better to get a list of goods and a buyer. Where should this download be? In what class?
And everything is the same, but only for the collection of orders.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-11-06
@qonand

1. Somehow your entities live a separate life from each other. In fact, now you have transferred the structure of your database to objects, and this is not correct. The order entity must aggregate the entities of the order and customer items, and not just contain their identifiers. For example:

class OrderEntity
{
    /**
     * @var integer Идентификатор заказа
     */
    protected $id;
    
    /**
     * @var MemberEntity Объект покупателя
     */
    protected $member;
    
    /**
     * @var ItemEntity Массив позиций заказа
    protected $items = [];
}

2. Getting data from the database into an object must be implemented in some repository or some datamapper. Read about these patterns. But in general it is better to take some sane ORM to avoid a heap of crap.
3. By class names - do not add the Entity suffix to them, the code becomes more heaped because of this, better use namespaces

D
dmitriy, 2017-11-13
@dmitriylanets

I had attempts to implement a datamapper , as part of the study, but in fact I need something more ready-made, stable. If you find a lib for mapping data, please share.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question