jeudi 9 juin 2016

PHP Data mapper - map multiple domain objects together

I'm developing a page where users can see an overview of graphical images that represent Internet traffic coming in and going out of a network device's ports. Information about these ports are collected in a table. This table has at least the following columns per port:

  • Port ID
  • Device ID
  • PortName
  • and more...

The Device ID column is the primary key of another table: Devices. This table has at least the following columns:

  • Device ID
  • DeviceName
  • and more...

As you can see, there is a relation between these two tables by Device ID. I have translated both tables to Domain Objects 'Port' and 'Device'. Both Domain Objects get populated by two Domain Mappers 'PortMapper' and 'DeviceMapper'. One attribute I need from every port is the DeviceName which I can get through Device ID. My question is about how I can best map these two Domain objects together.

My PortMapper's findById() function looks like this:

public function findById($id, DeviceMapper $deviceMapper) {
    $ports = $this->db->sql_select('SELECT * FROM ports WHERE customer_id = ?', [$id]);

    $arrayOfPorts = [];

    foreach($ports as $port) {   
        $device = $deviceMapper->findById($port['device_id']);
        $port['device'] = $device;
        $arrayOfPorts[] = $this->createObject($port);
    }

    return $arrayOfPorts;
}

And my DeviceMapper's findById() function:

public function findById($id) {
    $device = $this->db->sql_select('SELECT * FROM devices WHERE device_id = ?', [$id]);
    return $this->createObject($device);        
}

The way I instantiate this is in my Controller:

$portMapper = new PortMapper(new Database('librenms'));
$ports = $portMapper->findById(1000, new DeviceMapper(new Database('librenms')));

foreach($ports as $port) {
    echo $port->getDevice()->getHostname(); // echo here just for explanation
}

I get the Device's hostname per Port just fine. But the way I instantiate the whole thing is really bad. What would be a better approach to the relation between two Domain Objects?

Aucun commentaire:

Enregistrer un commentaire