根据 Haim Evgi 的评论,我创建了一个控制器插件,它根据请求方法添加 Zend_Controller_Router_Route 路由。这是该控制器插件的代码:
class TW_Webservice_Controller_Plugin_RestRoutes extends Zend_Controller_Plugin_Abstract
{
/**
*
* @var Zend_Controller_Router_Interface
*/
public $router;
/**
* Setup Rest routes that are not handled by the default Zend_Rest_Route object.
*
* @param Zend_Controller_Request_Abstract $request
*/
public function routeStartup(Zend_Controller_Request_Abstract $request)
{
$front = Zend_Controller_Front::getInstance();
$this->router = $front->getRouter();
$method = strtolower($request->getMethod());
$restRoutes = array(
'/event/signup' => 'event-signup'
);
$this->addRoutes($method, $restRoutes);
}
/**
*
* @param string $method The request method
* @param array $restRoutes Router pattern => Controller name pairs
*/
public function addRoutes($method, $restRoutes)
{
foreach ($restRoutes as $routePattern => $controllerName) {
switch ($method) {
case "get":
$this->addGetRoutes($routePattern, $controllerName);
break;
case "post":
$this->addPostRoute($routePattern, $controllerName);
break;
case "put":
$this->addPutRoute($routePattern, $controllerName);
break;
case "delete";
$this->addDeleteRoute($routePattern, $controllerName);
break;
}
}
}
/**
*
* @param string $routePattern
* @param string $controllerName
*/
public function addGetRoutes($routePattern, $controllerName)
{
$this->addRestRoute($routePattern, $controllerName, 'index');
$routePattern = $routePattern . '/:id';
$this->addRestRoute($routePattern, $controllerName, 'get');
}
/**
*
* @param string $routePattern
* @param string $controllerName
*/
public function addPostRoute($routePattern, $controllerName)
{
$this->addRestRoute($routePattern, $controllerName, 'post');
}
/**
*
* @param string $routePattern
* @param string $controllerName
*/
public function addPutRoute($routePattern, $controllerName)
{
$routePattern = $routePattern . '/:id';
$this->addRestRoute($routePattern, $controllerName, 'put');
}
/**
*
* @param string $routePattern
* @param string $controllerName
*/
public function addDeleteRoute($routePattern, $controllerName)
{
$routePattern = $routePattern . '/:id';
$this->addRestRoute($routePattern, $controllerName, 'delete');
}
/**
*
* @param string $routePattern
* @param string $controllerName
* @param string $action
*/
public function addRestRoute($routePattern, $controllerName, $action)
{
$route = new Zend_Controller_Router_Route($routePattern, array(
'controller' => $controllerName,
'action' => $action
));
$this->router->addRoute($controllerName . '-' . $action, $route);
}
}
如果从配置文件中检索 $restRoutes 数组会更好,但现在这可行。