Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

php - Calling member function of other controller in zend framework?

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

Here's another controller

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

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

Solution

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();
    } 
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...