1

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

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在模块中实现代码重用,并在模块中添加另一个方法,该方法仅对模块可用。有没有办法做到这一点,而无需将代码复制到模块中的模块中?mobileindexAction()pageAction()IndexControllerwebpaperAction()**mobile**mobileIndexController.phpwebmobile

谢谢

4

3 回答 3

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...
    }
}

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

应用程序/模块/web/controllers/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.

另一种选择是使其中一个控制器(网络或移动)成为另一个扩展的控制器。有关如何执行此操作的示例,请参阅此答案Share zend module controllers for use in another module 。它是相似的,你只需要正确的控制器文件,你就可以从它扩展。

于 2012-05-02T00:32:15.460 回答
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');
}
于 2013-06-10T19:25:52.910 回答
0

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

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

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

于 2012-05-01T23:33:31.217 回答