3
votes

Trips hasMany Legs hasMany Segments

In my flight search app, I've got a function that returns unique Leg.destination(s). This function is for a trip controller method. Do I put the function in the trip model or leg model? If in the leg model I call it with $this->Trip->Leg->findUniqueDests.....? I'm asking because I want to stick to CakePHP convention. Thanks!

//code that finds ALL destinations for each Leg
$destinations=$this->Trip->Leg->find('all', array('limit'=>100,'fields'=>'Leg.destination'));

//code that finds the unique destinations (to be used to search all flights for a particular city
function findUniqueDests($destinations){
  $unique_destinations = array();
  foreach ($destinations as $dest)
  {
      if(!in_array($dest, $unique_destinations))
      {
          $unique_destinations[] = $dest;
          sort($unique_destinations);
      }
  }
  return $unique_destinations;

}

1
many legs, many segments per leg, flights... Does your app control flying centipedes? :P I would think this is best in the model.FrustratedWithFormsDesigner
We pull all of the data that Kayak provides for now. Agreed that some might be excessive.JohnAllen
Fat Model Skinny Controller, it often helps me keep my code in check :)serialk

1 Answers

3
votes

Yes, you would put it in the Leg model. This will allow you to call the method from any other related model:

// Trip Controller
$this->Trip->Leg->findUniqueDests($destinations);

// Leg Controller
$this->Leg->findUniqueDests($destinations);

// Segment Controller
$this->Segment->Leg->findUniqueDests($destinations);

Kudos to you for knowing that it should be in a Model. Many people starting with CakePHP cram all of their methods in the controllers.

Doing it in the Model this way allows you to re-use the code all over the application. In reality, this kind of utility function could be placed in any model. But since it is dealing with Legs, the most logical home would be the Leg model.

Question: Why are you sorting every time a destination is added to the array? This would be more optimized:

function findUniqueDests($destinations) {
    $unique_destinations = array();
    foreach ($destinations as $dest) {
        if(!in_array($dest, $unique_destinations)) {
            $unique_destinations[] = $dest;
        }
    }
    return sort($unique_destinations);
}