0

我有 2 个控制器:UsersController 和 AnalyticsController。

当我运行时:

//UsersController:
function dummyFunction(){
    $this->Analytic->_loadChartFromId($chart_id);
}

输出是:

Query: _loadChartFromId 

警告(512):SQL 错误:1064:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“_loadChartFromId”附近使用正确的语法 [CORE\cake\libs\model\datasources\dbo_source.php,第 684 行]

_loadChartFromId()函数将 $chart_id 作为参数并返回一个数组作为输出。我不知道为什么会Query: _loadChartFromId出现。

4

2 回答 2

0

I could have opted to close this question as an exact duplicate of at least 5 other questions (if you search for "cakephp another controller"). But the answers there are just terrible. They actually try to invoke new Dispatchers or requestAction().

So if your question is about another controller method:

The short answer is: You don't.

The long answer: You still dont. That's a typical beginners mistake. You should put the functionality into a component if it is mainly business logic. The component then can be accessed from multiple controllers.

If it is more like model data (as in your example), put the functionality into the model layer (in an appropriate model). this way you can also access it from anywhere in your application.

Also: Accessing protected methods from other objects is never a good idea. Use public methods if you intend to use it from "outside" the object.

If your question is about a model method: You need to include your model in your controller before you can use it. Either by using public $uses or by using loadModel('ModelName') or even ClassRegistry::init('ModelName').

于 2013-01-04T09:21:28.410 回答
0

您不会从控制器调用其他控制器方法。

在您的用户控制器中,$this->Analytic是分析模型的实例,而不是 AnalyticsController。因此,CakePHP 认为您正在尝试调用_loadChartFromId()在分析模型上调用的公共方法,如您所知,该方法不存在。

您收到错误的原因是,如果您尝试调用模型的不存在方法,CakePHP 会尝试将其转换为其Magic Find Types之一。当然,它也不是有效的 Magic Find 类型,所以会出现 SQL 错误。

解决方案

由于我们只有您的部分代码,因此很难提供完整的解决方案,但是您在编写应用程序的方式上可能违反了 MVC 的概念。

您需要做以下两件事之一:

  1. 移动_loadChartFromId()到您的用户控制器。在我看来,这似乎是违反直觉的,因为它可能与用户无关。

  2. 将该方法移至您的分析模型。您需要将其公开,以便控制器可以访问它,并且在您的用户控制器中,您需要确保已加载分析模型。

    class Analytic extends AppModel {
    
        public function _loadChartFromId($chart_id) {
           // ...
        }
    }
    

    然后,您可以像以前一样从您的用户控制器调用该方法。

于 2013-01-04T12:15:44.580 回答