繁体   English   中英

Joomla:从模型中调用辅助函数?

[英]Joomla: Call helper function from within a model?

我开始使用php和Joomla开发,并发现在Joomla中工作很难做一些相当简单的事情。 通过Joomla MVC示例和Lynda(到目前为止已经构建了一些简单的视图)。

我有一个帮助文件/类/函数,它输出“已完成”表中存在的所有用户ID,因此我可以显示基于该用户的新记录的链接或编辑现有用户的记录。

我已经在该帮助文件中成功地在组件的不同部分使用了不同的函数( Joomla:在组件中编写和调用辅助函数 )。

当我在模型中做同样的事情时,我得到这个:“致命错误:从C:\\ wamp \\ www \\ ilplocal \\ libraries \\ joomla \\ application中的上下文'JView'调用受保护的方法JModel :: _ createFileName()第773行上的\\ component \\ view.php“。 当我在视图中尝试它,工作正常 - 但我需要模型中的输出。

码:

lookups.php

abstract class LookupHelper {

    public function other_functions($vars){
        ...
    }

    public function completions_exist() {

        $db =& JFactory::getDBO();            
        $query = $db->getQuery(true);

        $query->SELECT(' #__completed.completed_userid as UserID');
        $query->FROM (' #__completed');
        $query->GROUPBY (' #__completed.completed_userid ');

       $db->setQuery($query);    
       $result = $db->loadResultArray(0); 

       return $result;                        

    }        
}

在模型中:

$completions_exist = Jview::loadHelper('lookups'); 
$completions_exist = LookupHelper::completions_exist();

这一行$completions_exist = Jview::loadHelper('lookups');错误: $completions_exist = Jview::loadHelper('lookups');

我发现了一些非常模糊的引用,称为JLoader :: register以引入辅助函数,但在Joomla中找不到任何好的文档,除非每个人都说要使用它。 所以我试着这样使用它:

 JLoader::register('LookupHelper', dirname( JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php');
 $completions_exist = LookupHelper::completions_exist();

抛出此错误:“致命错误:在C:\\ wamp \\ path \\ to \\ model \\ not \\ to \\ lookups.php中找不到类'LookupHelper'。尝试操作JLoader :: register(这里的所有内容)并且它没有' t影响错误消息的路径。

思考? 为什么它在视图中工作而不在模型中? 如何在模型中使用辅助函数?

谢谢!

#####编辑

感谢@cppl看起来像第二位代码的路径问题。 我也读到了.DS。 在将来的版本中将逐步删除表示法 - 所以正在运行的代码是:

 JLoader::register('LookupHelper', JPATH_COMPONENT_ADMINISTRATOR.'/helpers/lookups.php'); $completions_exist = LookupHelper::completions_exist(); 

让我们打破这个:

  1. 在Joomla! 你的组件助手文件应该在`/mycomponent/helpers/lookup.php'中

  2. JLoader::是Joomla! 这样做的方法,但你可以很容易地使用PHP的require_once例如。 require_once JPATH_COMPONENT_ADMINISTRATOR.'/helpers/myfunctions.php';

  3. 你的路径对吗? - 你提供了dirname(JPATH_COMPONENT_ADMINISTRATOR).DS.'helpers'.DS.'lookups.php'但是你已经在dirname包装了你的组件的路径,它只是路径的父元素 所以JLoader正在查看/administrator/helpers/lookups.php

  4. JPATH_COMPONENT_ADMINISTRATOR初始化为Joomla!的renderComponent()调用它的JComponentHelper类中的一部分,如果你在它未设置时应用dirname你会得到一个点(即当前目录),所以在模型中你可以传递./helpers/lookups.phpJLoader调用。

您可以通过以下方法在模型中调用helper:

JLoader::import('helpers.events', JPATH_COMPONENT);

这将包括组件目录中的文件helpers / events.php。

$_helper = new EventsHelper(); echo $_helper->getAnyInsideMethod();exit;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM