本文介绍了某个功能应该在哪里建模或控制器? CakePHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Trips hasMans Legs hasMany Segments

Trips hasMany Legs hasMany Segments

在我的航班搜索应用中,我有一个返回唯一Leg.destination(s)的函数.该功能适用​​于跳闸控制器方法.是否将功能放入行程模型或腿部模型中?如果在腿模型中,我用$ this-> Trip-> Leg-> findUniqueDests .....来称呼它?我问是因为我想坚持CakePHP约定.谢谢!

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;

}

推荐答案

是的,您可以将其放在Leg模型中.这将允许您从任何其他相关模型中调用该方法:

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);

您应该知道它应该在模型中,因此对您表示敬意.从CakePHP开始的许多人都在控制器中塞满了所有方法.

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.

以这种方式在模型中进行操作使您可以在整个应用程序中重复使用代码.实际上,这种效用函数可以放置在任何模型中.但是,由于它处理的是Legs,所以最合逻辑的家就是Leg模型.

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);
}

这篇关于某个功能应该在哪里建模或控制器? CakePHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 22:25