Dealing with nested objects (nesting) using a ORM

Asked

Viewed 104 times

3

Let’s assume that in a system for a bus company I have entities: Line, car and travel.
Each one has three classes:

The entity itself,

class Linha extends Model
{
   protected $id;
   // outras propriedades.

   public function getId() {
       return $this->id;
   }
   // outros métodos.

Your collection,

class LinhaCollection extends ArrayObject {}

And his mapper.

class LinhaMapper extends Mapper
{
    public function findAll() {
        $sql = "SELECT * FROM `linhas`";
        return $this->fetchCollection($sql); // Retorna uma coleção de objetos do tipo Linha.
}

So listing all the lines is very simple:

$lm = new LinhaMapper;
$linhas = $lm->findAll();

foreach ($linhas as $linha) {
    echo $linha->getNome();
}

/*
 * Linha 123
 * Linha 456
 * Linha 159
 */

I want to list in my View all lines, cars and trips as follows (tree type):

  • Line 123
    • Car 001
      • Voyage 1
      • Journey 2
    • Car 002
      • Voyage 1
      • Journey 2
  • Line 456...

What would be the best way to do that?

I’m sorry if the explanation was long, I’m a beginner and I don’t know if my solution is too obvious.
Codes have been simplified to shorten the question

  • Hi Lucas, you still need help in this matter?

  • Hello Fernando, yes I do. Thank you.

1 answer

1


Okay, you have the three independent entities isolated from each other. To assemble this tree you need one or two more entities in your database, suggestions according to my point of view:

1) Relating Lines and Cars. If a same Car can be in more than one Line it will be a relationship N:N, for example, a table Linha_Carro.

2) In the Travel entity you must have the Car ID, to know which car made each trip, assuming that each trip is only done once, and by a single Car.

So far we’re only talking about database modeling.

In the OO implementation of the Line class you must create an attribute that will be an array containing objects Car, example:

class Linha extends Model
{
   protected $id;

   /*
    * @var Carro[] Coleção dos carros vinculados à Linha.
    */
   protected $carros = array();
   // outras propriedades.

   public function getId() {
       return $this->id;
   }
   // outros métodos.

In your Mapper, when loading a Line object from the database, after popular the simple attributes you must populate the attribute $carros of the collection, running a SELECT in the table Linecar.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.