简体   繁体   中英

How to call custom controller from index controller in Zend Framework

I am newbie in Zend framework.And i have made sample project in netbeans.And it is working properly displaying index.phtml .But , I need to call my controller.What I have tried is below.

IndexController.php


<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {

    }

    public function indexAction()
    {
        firstExample::indexAction();
    }    

}

And I have deleted all the content of index.phtml(just a blank file) , coz i don't want to render this view. My custom controller is:

firstExampleController.php

<?php
class firstExample extends Zend_Controller_Action{
    public function indexAction(){
        self::sum();
    }

    public function sum(){
        $this->view->x=2;
        $this->view->y=4;
        $this->view->sum=x + y;
    }
}
?>

firstExample.phtml

<?php
echo 'hi';
echo $this->view->sum();
?>

How to display sum method in firstExample.php.

It just shows blank page after hitting below URL.

http://localhost/zendWithNetbeans/public/

I think after hitting on above URL , execution first goes to index.php in public folder.And I didn't change the content of index.php

You are using controller (MVC) incorrectly, Controller should not do any business logic, in your case sum method. Controller only responsible controlling request and glueing model and view together. That's why you have problems now calling it.

Create Model add method sum, and use in any controller you want. From controller you may pass model to view.

Here is example: http://framework.zend.com/manual/en/learning.quickstart.create-model.html it uses database, but it's not necessary to use with database.

Basically your sum example could look like:

class Application_Sum_Model {

 public function sum($x, $y) {
   return ($x + $y);
 }
}

class IndexContoler extends Zend_Controller_Action {

   public function someAction() {

    $model = new Application_Sum_Model(); 

    //passing data to view that's okay
    $this->view->y   = $y;
    $this->view->x   = $x;
    $this->view->sum = $model->sum($x, $y); //business logic on mode

   }
}

Please read how controller is working, http://framework.zend.com/manual/en/zend.controller.quickstart.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM