zendframework 基于GET参数的路由

zendframework routing based on the GET parameter

我的网站 (zendframework 1) 中有一个页面解析 GET 参数并从数据库中查询其数据以显示给用户。

-> my current url : https://example.com/index.php/product/info?id=123

我希望我的 url 更易于阅读

-> https://example.com/index.php/product/iphone-7s-white

所以基本上我想解析 url 中的 GET 参数并从数据库中查询产品名称,以使其显示为 url 中的页面名称。

我遇到了一些解决方案,其中一个是通过循环遍历数据库(在bootstrap.php中)并为每个产品添加一条路线来实现的,但这看起来很乱,(产品可以达到200k或可能不止于此)。

我的问题有更好的解决方案吗?提前致谢

所以基本上,ZF1 提供了一条默认路由,该路由通向 url 中的 controller/action 个名称。

您可以通过在 application/Bootstrap.php 文件中添加函数来添加自定义路由:

/**
 * This method loads URL routes defined in /application/configs/routes.ini
 * @return Zend_Router 
 */
protected function _initRouter() {
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $router = $front->getRouter();
    $router->addRoute(
        'user',
        new Zend_Controller_Router_Route('product/:slug', array(
            'controller' => 'product',
            'action'     => 'details',
        ), array(
            'slug' => '[A-Za-z0-9-]+',
        ))
    );
    return $router;
}

给你!


正如 Chris 所述,您需要更改控制器代码来处理请求。另一种解决方案是使用额外的操作。

final class ProductController
{
    public function infoAction()
    {
        $product = $table->find($this->_param('id'));
        $this->view->product = $product;
    }

    public function detailsAction()
    {
        $product = $table->fetch(['slug' => $this->_param('slug')]);
        $this->view->product = $product;
        $this->render('info');
    }
}

现在,假设您在 infoAction 中进行了大量处理,您可以使用转发:

final class ProductController
{
    public function infoAction()
    {
        $product = $table->find($this->_param('id'));
        $this->view->product = $product;
    }

    public function detailsAction()
    {
        $product = $table->fetch(['slug' => $this->_param('slug')]);
        $this->forward('info', 'product', [
            'id' => $product->id,
        ]);
    }
}

它的效率较低(2 个请求而不是一个),但允许您重用代码。