代码之家  ›  专栏  ›  技术社区  ›  Wouter Dorgelo voy

如何在Zend框架中创建自定义路由器?

  •  0
  • Wouter Dorgelo voy  · 技术社区  · 14 年前

    mytutorialsite.com/category/:类别名称

    # added to application.ini
    resources.router.routes.categorynameOnCategory.route = /category/:categoryname
    resources.router.routes.categorynameOnCategory.defaults.module = default
    resources.router.routes.categorynameOnCategory.defaults.controller = category
    resources.router.routes.categorynameOnCategory.defaults.action = categoryname
    

    我还有一个数据库表“categories”,其中存储了所有类别。例如,假设以下类别当前存储在我的数据库中:

    - html
    - css
    - js
    - php
    

    这意味着,存在以下页面:

    • mytutorialsite.com/category/html
    • mytutorialsite.com/category/js

    但是,当您访问数据库中未列出类别名称的页面时,例如:

    • mytutorialsite.com/category/foo

    你应该得到一个 404页不存在 信息。

    1 回复  |  直到 12 年前
        1
  •  1
  •   Jurian Sluiman    14 年前

    我认为您的意思是在您的路由中将categoryname用作操作:categoryname应该用作操作吗?有两种方法可以使用。首先,只向存在类别的路由器添加路由。当请求category/foo时,路由器将无法识别路由并抛出404错误。

    第二个选项是捕获所有category/*路由,并在操作中检查该类别是否存在。

    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
        // Get the router
        $router     = Zend_Controller_Front::getInstance()->getRouter();
    
        // Fetch all your categories
        $category   = new Application_Model_Category;
        $categories = $category->fetchAll();
    
        // Loop and add all individual categories as routes
        foreach ($categories as $category) {
            $route  = 'category/:' . $category->name;
            $params = array(
                'module'     => 'default',
                'controller' => 'category',
                'action'     => $category->name
            );
    
            $route = new Zend_Controller_Router_Route($route, $params);
            $router->addRoute($category->name, $route);
        }
    }
    

    另一种方法对路线更简单。在application.ini中:

    resources.router.routes.category.route      = "category/:action"
    resources.router.routes.category.module     = "default"
    resources.router.routes.category.controller = "category"
    

    现在,来自category/SOMETHING的所有请求都将转到默认模块category controller。调度程序检查操作是否存在某些内容。当它这样做时,它执行动作。否则,将引发Zend_控制器操作异常(“操作不存在”)。

    当然,routeStartup函数应该有一个缓存机制来防止对每个请求进行数据库查询。

    推荐文章