如何在Zend Framework中的两个模块中重用和覆盖控制器操作

时间:2012-05-01 23:05:11

标签: php model-view-controller zend-framework

我目前只有2个模块的Zend Framework模块化设置:

web
mobile

设置如下:

applications
--modules
----**web**
------controllers
--------IndexController.php
-----------function indexAction(){.......}
-----------function pageAction(){......}
------models
--------Model.php
------views
--------scripts
----------index.phtml
----**mobile**
------controllers
--------IndexController.php
------views
--------scripts
----------index.phtml

我希望在IndexController模块中的mobile中重复使用代码,方法是在{strong> {{1}的indexAction()中重用pageAction()IndexController }} 模块,并在web模块中添加另一个 paperAction() 方法,该方法仅适用于**mobile**模块。有没有办法在mobile模块的IndexController.php模块的web中复制代码?

由于

3 个答案:

答案 0 :(得分:1)

根据您的需求,您可以创建一个基本控制器,每个模型的索引控制器将从中扩展。在基本控制器中,定义您希望在两者之间共享的最小功能。

或者,让其中一个模块控制器成为主模块,让其他模块控制器从中扩展。

在第一个例子中,你会做这样的事情:

应用/控制器/ IndexBaseController.php

<?php
class IndexBaseController extends Zend_Controller_Action {
    public function indexAction() {
        // shared code for both modules' indexaction here...
    }

    public function pageAction() {
        // shared code for both modules' pageaction here...
    }
}

然后,从这个扩展两个模块控制器:

应用/模块/网络/控制器/ IndexController.php

<?php
require_once APPLICATION_PATH . '/controllers/IndexBaseController.php';

class Web_IndexController extends IndexBaseController {
    // other actions here, this already contains indexAction and pageAction()
}

然后对mobile/controllers/IndexController.php执行相同操作。

另一种选择是使控制器(web或移动设备)中的一个控制器与另一个控制器延伸。有关如何执行此操作的示例,请参阅此答案Share zend module controllers for use in another module。它类似,您只需要正确的控制器文件,以便从中扩展。

答案 1 :(得分:0)

是的,你可以随时实例化你的控制器并调用他们的方法

$web_ctlr=new Web_IndexController();
$web_ctlr->indexAction();
$web_ctlr->pageAction();

但问题在于你在行动中做了什么,因为这些动作是为了准备渲染。所以我猜你最终会有多个输出,特别是如果你在控制器构造函数中做一些html渲染。如果您从可重复使用的操作中返回有效数据,那么您现在应该可以。但是我建议你看看zend部分概念并决定哪一个适合你的情况

答案 2 :(得分:0)

实际上你唯一需要的就是这个(确保你在application.ini中设置了controllerDirectory):

<?php
class App_Controller_Action_Helper_RequestForward extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @return null
     */
    public function direct($moduleName)
    {
        //this is basically the application.ini parsed & saved in Zend Registry
        $config = Zend_Registry::get('config');

        $controllersPath = $config->resources->frontController->controllerDirectory->$moduleName;

        $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
        return $dispatcher->setControllerDirectory($controllersPath)->dispatch($this->getRequest(), $this->getResponse());
    }
}

然后在另一个模块的控制器中:

public function editAccountAction()
{
    return $this->_helper->RequestForward('default');
}