action parameters routing not working in Zend fram

2019-08-17 01:14发布

I'm trying to set up a route in Zend Framework (version 1.11.11) in a routes.ini file, which would allow be to match the following url:

my.domain.com/shop/add/123

to the ShopController and addAction. However, for some reason the parameter (the number at the end) is not being recognized by my action. The PHP error I'm getting is

Warning: Missing argument 1 for ShopController::addAction(), called in...

I know I could set this up using PHP code in the bootstrap, but I want to understand how to do this type of setup in a .ini file and I'm having a hard time finding any resources that explain this. I should also point out that I'm using modules in my project. What I've come up with using various snippets found here and there online is the following:

application/config/routes.ini:

[routes]
routes.shop.route = "shop/add/:productid/*"
routes.shop.defaults.controller = shop
routes.shop.defaults.action = add
routes.shop.defaults.productid = 0
routes.shop.reqs.productid = \d+

Bootstrap.php:

... 
protected function _initRoutes() 
    {
        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/routes.ini', 'routes');
        $router = Zend_Controller_Front::getInstance()->getRouter();
        $router->addConfig( $config, 'routes' );
    }
...

ShopController.php

<?php

class ShopController extends Egil_Controllers_BaseController
{

    public function indexAction()
    {
        // action body
    }

    public function addAction($id)
    {
        echo "the id: ".$id;
    }

}

Any suggestions as to why this is not working? I have a feeling I'm missing something fundamental about routing in Zend through .ini files.

1条回答
三岁会撩人
2楼-- · 2019-08-17 01:51

Apparently I'm more rusty in Zend than I thought. A few minutes after posting I realized I'm trying to access the parameter the wrong way in my controller. It should not be a parameter to addAction, instead I should access it through the request object inside the function:

correct addAction in ShopController:

public function addAction()
{
    $id = $this->_request->getParam('productid');
    echo "the id: ".$id;
}

I also realized I can simplify my route setup quite a bit in this case:

[routes]
routes.shop.route = "shop/:action/:productid"
routes.shop.defaults.controller = shop
routes.shop.defaults.action = index
查看更多
登录 后发表回答