教程:如何创建一个MVC模式的Joomla组件(二)

创建组件

对于这个简单的组件,只需5个文件:

hello.php - 组件的入口文件
controller.php - controller基类
views/hello/view.html.php - 返回数据,传递给模板
views/hello/tmpl/default.php - 模板文件
hello.xml - 组件安装文件

创建入口文件
Joomla!总是有一个单一的如楼,比如对于站点应用是/index.php,而对于管理应用是/administrator/index.php,根据URL或者POST数据中option参数,来决定载入必要的组件。我们开发的这个组件的入口:index.php?option=com_hello&view=hello

这就会载入我们的主文件,也就是组件的入口文件 components/com_hello/hello.php.

以下的代码对于所有的组件是相当典型的:

<?php
/**
 * @package    Joomla.Tutorials
 * @subpackage Components
 * components/com_hello/hello.php
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
 * @license    GNU/GPL
*/

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

// Require the base controller

require_once( JPATH_COMPONENT.DS.'controller.php' );

// Require specific controller if requested
if($controller = JRequest::getWord('controller')) {
    $path = JPATH_COMPONENT.DS.'controllers'.DS.$controller.'.php';
    if (file_exists($path)) {
        require_once $path;
    } else {
        $controller = '';
    }
}

// Create the controller
$classname    = 'HelloController'.$controller;
$controller   = new $classname( );

// Perform the Request task
$controller->execute( JRequest::getVar( 'task' ) );

// Redirect if set by the controller
$controller->redirect();

?>

第一句声明是一个安全检查。

JPATH_COMPONENT 当前组件的绝对路径, 对于这个组件是 components/com_hello.

DS 是系统目录分隔符:  ‘/’ 或 ‘\’,由系统自动设置,从而开发者不必担心系统和版本的问题。

在controller载入后,要检查是否有特别的controller需要载入。本例中没有,但是我们保留以备后用。

JRequest::getVar() 是获取get或post的数据. 如果url: index.php?option=com_hello&controller=controller_name,JRequest::getVar(’controller’)就可以返回controller的名字;

controller命名规则是‘{Componentname}{Controller}{Controllername}’

创建了controller后, 就要执行任务,url: index.php?option=com_hello&task=sometask. 如果没有指定task,那么就执行display,这时view决定显示什么。

controller可以转向, 比如保存任务完成后. 最后一行程序就是监测转向.

转载于:https://www.cnblogs.com/vicenteforever/articles/1633000.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值