模块是页面扩展轻量级方式,相对组件更为灵活。模块通常用来做页面中不太复杂的一小块,并且能够跨越不同的组件。
在Joomla的标准安装后,你可以看到许多模块的例子,菜单,最新新闻,登录框等等
这个教程阐述如何编写一个简单的 Hello world 模块,通过这个教程,你可以学到一个模块的基本文件结构。而通过基本机构可以扩展生成更为复杂的模块。
文件架构
标准的模块开发共有四个基本文件,
mod_helloworld.php - 模块的主入口,主要执行一些必须的初始化工作,调用helper或缺必要的数据,并引入模板。
mod_helloworld.xml - 这个文件主要包含模块的信息,主要定义安装时必须的文件以及模块的参数。
helper.php - 这个文件包含 helper 类,这个类主要用来获取模块要显示的信息(通常是从数据库或其他的源)
tmpl/default.php - 模块的模板,这个文件采用mod_helloworld.php返回的数据生成页面要显示的html
创建 mod_helloworld.php
mod_helloworld.php 主要进行以下工作:
引入helper.php文件,helper.php文件包含是获取必要数据的类
调用合适的helper类,并返回数据。
引入模板
The helper class is defined in our helper.php file. This file is included with a require_once statement:
helper 类在helper.php中定义,这个文件通过 require_once 声明来引入:
require_once( dirname(__FILE__).DS.'helper.php' );
我们的helper类现在还没定义,但是以后你可以看到,包含一个方法 getHello()。对于我们这个简单的例子,这样做并不是必须的,因为这个方法返回的信息“Hello, World”可以直接简单的包含在模板中。我们这里这样做主要是为了战士这项技术。
我们的模块现在没有用到参数,但是为了以后扩展模块的时候方便,我们吧参数传递给 helper的方法。
helper 类的方法用以下的方式调用:
$hello = modHelloWorldHelper::getHello( $params );
完整的 mod_helloworld.php 文件
<?php
/**
* Hello World! Module Entry Point
*
* @package Joomla.Tutorials
* @subpackage Modules
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @license GNU/GPL, see LICENSE.php
* mod_helloworld is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
// Include the syndicate functions only once
require_once( dirname(__FILE__).DS.'helper.php' );
$hello = modHelloWorldHelper::getHello( $params );
require( JModuleHelper::getLayoutPath( 'mod_helloworld' ) );
我们还没有解释第一行,第一行主要是定义这个文件属于一个Joomal应用,并用来防止注射和其他潜在的风险。