phpzend-frameworkzend-framework-mvc

How to properly call controller/action in Zend Framework 1?


I have the following directory structure in a Zend Framework 1 application:

application/
├── controllers/
│   └── admin/
│     └── TaxRateController.php
│   └── MainInitController.php

I am trying to access taxrate which should be indexAction() but I am doing something wrong since I am getting a Zend_Controller_Action_Exception. This is what I have tried all this URL combination so far:

http://localhos/admin/tax-rate/index
http://localhos/admin/tax-rate
http://localhos/admin/taxrate
http://localhos/admin/taxrate/index

And all of them generates the same error:

[message:protected] => Action "taxRate" does not exist and was not trapped in __call()

This is the content of the class(es):

class TaxRateController extends MainInitController
{
    public function indexAction()
    {
        echo 'I am here'; die();
    }
}

class MainInitController extends Zend_Controller_Action {
    ....
}

What I am missing here? How I should be calling the controller/action?

Update 1:

I have tried to move the directory outside controllers but the result is the same:

application/
│   └── admin/
│     └── TaxRateController.php
├── controllers/
│   └── MainInitController.php

I am calling as http://localhost/admin/taxrate in this scenario.


Solution

  • With basic structure it will take time and effort to do that but it can be done

    application/
    ├── controllers
    │   └── admin
    │       └── TaxRateController.php
    

    You need to create routes for every controller under sub directory in your bootstrap:

    public function _initAdminRoute()
        $router = Zend_Controller_Front::getInstance()->getRouter();
    
        // structure
        $router->addRoute(
                'unique_route_name',
                new Zend_Controller_Router_Route('/admin/controllerRoute/:action/*', 
                    ['controller' => 'subdirName_controllerRoute']
                )
        );
    
        // Like this
        $router->addRoute(
                'admin_taxrate_route',
                new Zend_Controller_Router_Route('/admin/tax-rate/:action/*', ['controller' => 'admin_tax-rate'])
        );
    }
    

    After this you need to rename your controller classes with subdirectory name to let zend find them. But do not change controller file names.

    class TaxRateController => class Admin_TaxRateController
    

    Now you can use your controllers, but a little fix may be needed for your views cause right now zend can not find your view directory. You need to move all your admin views to admin subdirectory or it will throw an error something similar to this.

    Fatal error: Uncaught exception 'Zend_View_Exception' with message 'script 'admin/tax-rate/action.phtml' not found in path (application/views/scripts/)' in

    Hope this helps, but still i will recommend using module structure.