在cakepp中为模型添加一个自定义函数


adding a custom function to a model in cakephp

我有一个具有位置属性的用户表,并希望创建一个检索附近用户(在给定半径内)的模型函数。这是我的型号:

类用户扩展AppModel{公共函数getNearbyUsers($id,$dist=10){return$this->query(…);}}

这是我的控制器,我正在尝试调用函数:

类UsersController扩展AppController{公共函数getNearbyUsers($id){。。。$this->User->getNearbyUsers($id)。。。}}

然而,这样做会导致:PHP Fatal error: Call to a member function getNearbyUsers() on a non-object

我做错了什么?


编辑:没关系,它不再抱怨了。但它抛出了一个SQL错误,我的模型函数实际上从未被调用过。在进一步检查mysql查询日志时,我看到了以下内容:

从`xxx查询SHOW TABLES`查询getNearbyUsers退出


CakePHP似乎将$this->User->getNearbyUsers解释为一个文本查询。所以我的问题仍然存在:如何在Cake中为模型添加自定义函数?

请参阅http://book.cakephp.org/2.0/en/models/additional-methods-and-properties.html:

虽然CakePHP的模型函数应该能让您找到需要的地方,不要忘记,模型类只是:允许编写自己的方法或定义自己的属性。

任何处理数据保存和获取的操作都是最好的放在你的模特班里。这个概念通常被称为脂肪模型。

型号

class Example extends AppModel {
    function getRecent() {
        $conditions = array(
            'created BETWEEN (curdate() - interval 7 day) and (curdate() - interval 0 day)'
        );
        return $this->find('all', compact('conditions'));
    }
}

这个getRecent()方法现在可以在控制器中使用。

控制器

$recent = $this->Example->getRecent();

代码中需要一些附加项,否则将出现非对象错误。

应用程序模型中:

<?php
class Get extends AppModel {
    public function getRecent() {
        // $conditions = array(
            // 'created BETWEEN (curdate() - interval 7 day)' .
            // ' and (curdate() - interval 0 day))'
        // );
        // return $this->find('all', compact('conditions'));
    }
}

在应用程序控制器中,

?php

class GetsController extends AppController {
    public $uses = array('Get');  // Needed, or the error will appear.
    public function Example () {
       $this->Get->getRecent();
    }
}

Cake 1.3也有同样的问题,使用插件(模块),即使我们的模型名称在整个应用程序中是唯一的(一些模型名称在多个插件中使用),它也只有在我请求控制器的$uses数组中的模型时才起作用,就像这样:'Module1.A'

app/plugins/plugin1/controllers/a_controller.php:

class AController extends AppController {
    // using simple array('A') worked fine for cake methods (find, query ...)
    // but did not recognized the custom method
    public $uses = array('Plugin1.A');
    public function Example () {
       $this->A->customMethod();
    }
}

app/plugins/plugin1/models/a.php:

<?php
class A extends AppModel {
    public function customMethod() {
        // ...
    }
}