【问题标题】:Kohana Route for API - Subdirectories, ids, formats用于 API 的 Kohana Route - 子目录、ID、格式
【发布时间】:2012-06-12 19:11:10
【问题描述】:

我正在尝试在 Kohana 3.2 中创建一个匹配 URI 的路由

api/article/get.json

api/article/get/123.xml

api/blogpost/post.json

api/user/get/username.json

所以我的想法是我有一个名为 API 的子目录,其中有我所有的 api 控制器,路由与控制器、方法、格式以及 ID 匹配。

我在application/bootstrap.php 中设置了以下路由

Route::set('api', 'api/<controller>(/<action>(/<id>).<format>)',
  array(
    'format' => '(xhtml|xml|json|rss|html|php|serialize)',
  ))
  ->defaults(array(
    'directory' => 'api',
    'controller' => 'blogposts',
    'action' => 'get',
    'format' => 'json',
  ));

我玩过这条路线的多种组合,但每次我都会收到以下错误消息,例如:localhost/api/blogposts/post.json

HTTP_Exception_404 [ 404 ]: The requested URL api/blogposts/post.php was not found on this server.

在我看来这应该没问题,但我一定做错了什么。

感谢您的帮助。

一个人

编辑

我的默认控制器设置为最后一个,只是想我会提到它,因为我在 SO 中找到了这篇文章 Kohana 3 route not matching

【问题讨论】:

    标签: api directory routes format kohana-3.2


    【解决方案1】:

    这可能是一个新手错误,但问题不在于路由,而是这里的类名是原因:

    我把控制器放在了

    application/classes/controller/api/bloposts.php
    

    班级的名字是

    class Controller_Blogposts extends Controller {
      ...
    }
    

    花了一些时间调试应用程序后,我发现问题不在于路由,而在于应该是类的名称

    class Controller_Api_Blogposts extends Controller {
      ...
    }
    

    因为自动加载器会将路由 api/blogposts.json 映射到类“Controller_Api_Blogposts”。

    在 Kohana 3.2 Conventions and Coding Style 中,他们有一个很好的表格,显示类名是什么以及文件路径应该是什么:

    我不确定 100% 使用目录进行路由映射背后的技术细节,但如果路由映射到 &lt;directory&gt;(在本例中为 api),则可以安全地假设 api 位于“application/classes/controller”目录中。

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 2011-10-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多