在zend框架中调用其他控制器的成员函数吗? [英] Calling member function of other controller in zend framework?

查看:86
本文介绍了在zend框架中调用其他控制器的成员函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在zend框架中调用另一个控制器的成员函数,如果可以,怎么办?

Is it possible to call the member function of another controller in zend framework, if yes then how?

<?php
class FirstController extends Zend_Controller_Action {
    public function indexAction() {
         // general action 
    }   

    public function memberFunction() {
         // a resuable function
    }
}

这里是另一个控制器

<?php
class SecondController extends Zend_Controller_Action {
    public indexAction() {
         // here i need to call memberFunction() of FirstController
    }
}

请说明我如何从第二个控制器访问memberFunction().

Please explain how i can access memberFunction() from second controller.

更好的主意是定义一个AppController,并使所有常用的控制器扩展AppController,从而进一步扩展Zend_Controller_Action.

Better idea is to define a AppController and make all usual controllers to extend AppController which further extends Zend_Controller_Action.

class AppController extends Zend_Controller_Action {
    public function memberFunction() {
         // a resuable function
    }
}

class FirstController extends AppController {
    public function indexAction() {
         // call function from any child class
         $this->memberFunction();
    } 
}

现在,作为简单继承的规则,可以从扩展AppController的控制器中调用memberFunction.

Now memberFunction can be invoked from controllers extending AppController as a rule of simple inheritance.

推荐答案

控制器并非旨在以这种方式使用.如果要在当前控制器之后执行另一个控制器动作,请使用_forward()方法:

Controllers aren't designed to be used in that way. If you want to execute an action of the other controller after your current controller, use the _forward() method:

// Invokes SecondController::otherActionAction() after the current action has been finished.
$this->_forward('other-action', 'second');

请注意,这仅适用于 action方法("memberAction"),不适用于任意成员函数!

Note that this only works for action methods ("memberAction"), not arbitrary member functions!

如果SecondController::memberFunction()在多个控制器之间执行了某些所需的操作,则将该代码放在动作帮助程序或库类中,以便两个控制器都可以访问共享功能,而不必彼此依赖.

If SecondController::memberFunction() does something that is needed across multiple controllers, put that code in a action helper or library class, so that both controllers can access the shared functionality without having to depend on each other.

这篇关于在zend框架中调用其他控制器的成员函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆