如何从PHP Cake 1.1中的常规控制器访问插件模型

时间:2010-04-28 17:10:49

标签: php model-view-controller cakephp

希望这是一个简单的问题:我有一个使用一组表(kb_items,kb_item_tags等)的插件。我希望能够从另一个控制器(比如我的页面控制器)访问这些模型,因此:

class PagesController extends AppController{

function knowledgebase(){
  $items = $this->KbItem->findAll(...);
}

}

我承认有点违反规则(通过不将此控制器放在知识库插件中),但在这种情况下,这是一个自定义页面,不需要是知识库插件代码库的一部分。< / p>

如果您需要更多详细信息,请与我们联系。在此先感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

我必须自己做,并将模型名称放在'Uses'数组中确实有效。如果您不需要在多个控制器操作中访问模型,您还可以使用loadModel()仅在您需要的操作中访问它。例如,假设您只需要在给定控制器的view()动作中访问此模型:

function view() {
  // load the model, making sure to add the plug-in name before the model name
  // I'm presuming here that the model name is just 'Item', and your plug-in is called 'Kb'
  $this->loadModel('Kb.Item');

  // now we can use the model like we normally would, just calling it 'Item'
  $results = $this->Item->find('all');
  }

希望有所帮助。

答案 1 :(得分:1)

不确定它是否在1.1中如此工作,但在1.2+中,您在模型名称前加上插件名称和控制器使用数组中的句点:

class PagesController extends AppController
{
    var $uses = array('Page','Kb.KbItem');

    function knowledgebase()
    {
         // This now works
         $items = $this->KbItem->findAll();
    }
}

答案 2 :(得分:0)

只需将模型添加到控制器的$uses属性中:

class PagesController extends AppController
{
    var $uses = array('Page','KbItem');

    function knowledgebase()
    {
         // This now works
         $items = $this->KbItem->findAll();
    }
}
相关问题