例子二:
这个例子中,插件将调用模块,展示在文章最终页面中。个人觉得这个例子更有参考价值!
<?php
/**
* @version $Id: loadmodule.php 9764 2007-12-30 07:48:11Z ircmaxell $
* @package Joomla
* @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! 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.
* See COPYRIGHT.php for copyright notices and details.
*/
//You can not directly access the file when you put this code at the beginning:
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
//下面的程序在系统中注册了插件,检查正文中的内容,在合适的地方,将调用plgContentLoadModule函数调用
$mainframe->registerEvent( 'onPrepareContent', 'plgContentLoadModule' );
//函数代码
function plgContentLoadModule( &$row, &$params, $page=0 )
{
//访问数据库
$db =& JFactory::getDBO();
//检查是否应该执行这个插件的功能
if ( JString::strpos( $row->text, 'loadposition' ) === false ) {
return true;
}
//获取插件信息
$plugin =& JPluginHelper::getPlugin('content', 'loadmodule');
//查找正文中的的标签
$regex = '//i';
//获取参数
$pluginParams = new JParameter( $plugin->params );
//检查插件是否已经发布
if ( !$pluginParams->get( 'enabled', 1 ) ) {
$row->text = preg_replace( $regex, '', $row->text );
return true;
}
//查找所有正文中匹配的地方
preg_match_all( $regex, $row->text, $matches );
//匹配的总数
$count = count( $matches[0] );
//如果有匹配,那么就执行插件
if ( $count ) {
//取得参数
$style = $pluginParams->def( 'style', -2 );
plgContentProcessPositions( $row, $matches, $count, $regex, $style );
}
}
//正文内容匹配位置处理函数
function plgContentProcessPositions ( &$row, &$matches, $count, $regex, $style )
{
for ( $i=0; $i < $count; $i++ )
{
//处理匹配部分内容,去掉
$load = str_replace( 'loadposition', '', $matches[0][$i] );
$load = str_replace( '{', '', $load );
$load = str_replace( '}', '', $load );
$load = trim( $load );
//在匹配位置调用plgContentLoadPosition
$modules = plgContentLoadPosition( $load, $style );
$row->text = preg_replace( '{'. $matches[0][$i] .'}', $modules, $row->text );
}
//去除无关标记
$row->text = preg_replace( $regex, '', $row->text );
}
//调用模块的函数
function plgContentLoadPosition( $position, $style=-2 )
{
//获取document实例
$document = &JFactory::getDocument();
//加载模块
$renderer = $document->loadRenderer('module');
//加载参数
$params = array('style'=>$style);
$contents = '';
foreach (JModuleHelper::getModules($position) as $mod) {
$contents .= $renderer->render($mod, $params);
}
//返回模块内容
return $contents;
}