12

在 Kohana/CodeIgniter 中,我可以使用这种形式的 URL:

http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ...

然后读取我的控制器中的参数如下:

class MyController 
{
    public function method_name($param_A, $param_B, $param_C ...)
    {
        // ... code
    }
}

您如何在 Zend 框架中实现这一点?

4

5 回答 5

11

看一下 Zend_Controller_Router 类:

http://framework.zend.com/manual/en/zend.controller.router.html

这些将允许您定义 Zend_Controller_Router_Route 以您需要的方式映射到您的 URL。

索引控制器的索引操作有 4 个静态参数的示例是:

$router = new Zend_Controller_Router_Rewrite();

$router->addRoute(
    'index',
    new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' => 'index', 'action' => 'index'))
);

$frontController->setRouter($router);

在您定义了前端控制器后,这将添加到您的引导程序中。

一旦开始行动,您就可以使用:

$this->_request->getParam('param1');

在您的操作方法中访问值。

安德鲁

于 2008-10-02T10:13:47.303 回答
6

更新(2016 年 4 月 13 日): 我下面答案中的链接已移动并已修复。但是,以防万一它再次消失——这里有一些替代方法可以提供有关此技术的一些深入信息,并使用原始文章作为参考材料:


@Andrew Taylor的回应是处理 URL 参数的正确 Zend Framework 方式。但是,如果您想在控制器的操作中包含 URL 参数(如您的示例中所示) - 请查看Zend DevZone 上的本教程

于 2008-10-08T20:54:59.383 回答
4

我已经扩展Zend_Controller_Action了我的控制器类并进行了以下更改:

dispatch($action)方法替换

$this->$action();

call_user_func_array(array($this,$action), $this->getUrlParametersByPosition());

并添加了以下方法

/**
 * Returns array of url parts after controller and action
 */
protected function getUrlParametersByPosition()
{
    $request = $this->getRequest();
    $path = $request->getPathInfo();
    $path = explode('/', trim($path, '/'));
    if(@$path[0]== $request->getControllerName())
    {
        unset($path[0]);
    }
    if(@$path[1] == $request->getActionName())
    {
        unset($path[1]);
    }
    return $path;
}

现在对于像这样的网址/mycontroller/myaction/123/321

在我的操作中,我将获得控制器和操作之后的所有参数

public function editAction($param1 = null, $param2 = null)
{
    // $param1 = 123
    // $param2 = 321
}

URL 中的额外参数不会导致任何错误,因为您可以将更多参数发送到然后定义的方法。您可以通过 获得所有这些func_get_args() 并且您仍然可以getParam()以通常的方式使用它们。您的 URL 可能不包含使用默认名称的操作名称。

实际上我的 URL 不包含参数名称。只有他们的价值观。(就像问题一样)并且您必须定义路由以指定 URL 中的参数位置,以遵循框架的概念并能够使用 Zend 方法构建 URL。但是如果你总是知道你的参数在 URL 中的位置,你可以很容易地得到它。

这不像使用反射方法那么复杂,但我想提供的开销更少。

Dispatch 方法现在看起来像这样:

/**
 * Dispatch the requested action
 *
 * @param string $action Method name of action
 * @return void
 */
public function dispatch($action)
{
    // Notify helpers of action preDispatch state
    $this->_helper->notifyPreDispatch();

    $this->preDispatch();
    if ($this->getRequest()->isDispatched()) {
        if (null === $this->_classMethods) {
            $this->_classMethods = get_class_methods($this);
        }

        // preDispatch() didn't change the action, so we can continue
        if ($this->getInvokeArg('useCaseSensitiveActions') || in_array($action, $this->_classMethods)) {
            if ($this->getInvokeArg('useCaseSensitiveActions')) {
                trigger_error('Using case sensitive actions without word separators is deprecated; please do not rely on this "feature"');
            }
            //$this->$action();
            call_user_func_array(array($this,$action), $this->getUrlParametersByPosition()); 
        } else {
            $this->__call($action, array());
        }
        $this->postDispatch();
    }

    // whats actually important here is that this action controller is
    // shutting down, regardless of dispatching; notify the helpers of this
    // state
    $this->_helper->notifyPostDispatch();
}    
于 2011-07-21T13:13:32.053 回答
3

对于允许更复杂配置的更简单方法,请尝试这篇文章。总之:

创造application/configs/routes.ini

routes.popular.route = popular/:type/:page/:sortOrder
routes.popular.defaults.controller = popular
routes.popular.defaults.action = index
routes.popular.defaults.type = images
routes.popular.defaults.sortOrder = alltime
routes.popular.defaults.page = 1
routes.popular.reqs.type = \w+
routes.popular.reqs.page = \d+
routes.popular.reqs.sortOrder = \w+

添加bootstrap.php

// create $frontController if not already initialised
$frontController = Zend_Controller_Front::getInstance(); 

$config = new Zend_Config_Ini(APPLICATION_PATH . ‘/config/routes.ini’);
$router = $frontController->getRouter();
$router->addConfig($config,‘routes’);
于 2009-12-30T18:04:49.940 回答
1

最初发布在这里http://cslai.coolsilon.com/2009/03/28/extending-zend-framework/

我目前的解决方案如下:

abstract class Coolsilon_Controller_Base 
    extends Zend_Controller_Action { 

    public function dispatch($actionName) { 
        $parameters = array(); 

        foreach($this->_parametersMeta($actionName) as $paramMeta) { 
            $parameters = array_merge( 
                $parameters, 
                $this->_parameter($paramMeta, $this->_getAllParams()) 
            ); 
        } 

        call_user_func_array(array(&$this, $actionName), $parameters); 
    } 

    private function _actionReference($className, $actionName) { 
        return new ReflectionMethod( 
            $className, $actionName 
        ); 
    } 

    private function _classReference() { 
        return new ReflectionObject($this); 
    } 

    private function _constructParameter($paramMeta, $parameters) { 
        return array_key_exists($paramMeta->getName(), $parameters) ? 
            array($paramMeta->getName() => $parameters[$paramMeta->getName()]) : 
            array($paramMeta->getName() => $paramMeta->getDefaultValue()); 
    } 

    private function _parameter($paramMeta, $parameters) { 
        return $this->_parameterIsValid($paramMeta, $parameters) ? 
            $this->_constructParameter($paramMeta, $parameters) : 
            $this->_throwParameterNotFoundException($paramMeta, $parameters); 
    } 

    private function _parameterIsValid($paramMeta, $parameters) { 
        return $paramMeta->isOptional() === FALSE 
            && empty($parameters[$paramMeta->getName()]) === FALSE; 
    } 

    private function _parametersMeta($actionName) { 
        return $this->_actionReference( 
                $this->_classReference()->getName(), 
                $actionName 
            ) 
            ->getParameters(); 
    } 

    private function _throwParameterNotFoundException($paramMeta, $parameters) { 
        throw new Exception(”Parameter: {$paramMeta->getName()} Cannot be empty”); 
    } 
} 
于 2009-06-25T02:17:25.823 回答