php – Dealing with nested objects (nesting) using an ORM

Question:

Let's suppose that in a system for a bus company I have entities: Line, car and trips.
Each 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 your 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 pretty simple:

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

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

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

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

  • Line 123
    • car 001
      • Trip 1
      • trip 2
    • car 002
      • Trip 1
      • trip 2
  • Line 456…

What would be the best way to do this?

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

Answer:

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

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

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

So far we're just talking about database modeling.

In the OO implementation of the Line class you must create an attribute that will be an array containing Car objects, for 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 Row object from the database, after populating the simple attributes you must populate the $carros attribute from the collection, executing a SELECT on the Car_Line table.

Scroll to Top