问题
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:
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);
}
来源:https://stackoverflow.com/questions/4339979/where-should-a-certain-function-go-model-or-controller-cakephp