【发布时间】:2015-06-09 13:04:18
【问题描述】:
如何在 Slim 框架中对路由进行分类?
我的公共目录中有这些基本/前沿路线,
$app->get('/about', function () use ($app, $log) {
echo "<h1>About ", $app->config('name'), "</h1>";
});
$app->get('/admin', function () use ($app, $log) {
echo 'admin area';
require dirname(__FILE__) . '/../src/Admin/index.php';
});
// To generic
$app->get('/', function () use ($app, $log) {
echo '<h1>Welcome to ', $app->config('name'), '</h1>';
});
// Important: run the app ;)
$app->run();
如您所见,当路由在/admin 上时,它会在Admin 目录中加载index.php。
管理员/index.php,
// API group
$app->group('/admin', function () use ($app) {
// Contact group
$app->group('/contact', function () use ($app) {
// Get contact with ID
$app->get('/contacts', function () {
echo 'list of contacts';
});
// Get contact with ID
$app->get('/contacts/:id', function ($id) {
echo 'get contact of ' . $id;
});
// Update contact with ID
$app->put('/contacts/:id', function ($id) {
echo 'update contact of ' . $id;
});
// Delete contact with ID
$app->delete('/contacts/:id', function ($id) {
echo 'delete contact of ' . $id;
});
});
// Article group
$app->group('/article', function () use ($app) {
// Get article with ID
$app->get('/articles', function () {
echo 'list of articles';
});
// Get article with ID
$app->get('/articles/:id', function ($id) {
echo 'get article of ' . $id;
});
// Update article with ID
$app->put('/articles/:id', function ($id) {
echo 'update article of ' . $id;
});
// Delete article with ID
$app->delete('/articles/:id', function ($id) {
echo 'delete contact of ' . $id;
});
});
});
假设我的管理区域中有文章、联系人等模块。在每个模块中,我都有获取、放置、删除的路线。所以我按模块对它们进行分组,如Admin/index.php。但是当我在我的 url 上请求这些模块时,我得到了 404 页面,例如 http://{localhost}/admin/contact 我应该在我的浏览器上得到 list of articles 但我得到一个 404。
如果我将分组路由放在public/index.php 中,我不会遇到这个问题,但我不想让这个索引变得混乱,因为我有更多模块要添加。我更喜欢将路线分成不同的索引。
那么是否可以将分组的路由拆分到不同位置(目录)中的不同index.php。
或者也许这不是我在 Slim 中应该这样做的方式?如果是这样,Slim 解决这个问题的方法是什么?
【问题讨论】:
-
您没有为 /admin/contact 定义 GET 路由 您的代码中的联系人列表是 GET /admin/contact/contacts
-
我将它们放在不同的索引文件中并包含该文件。但我想这不是它在苗条中的工作方式......
-
可以在单独的文件中定义路由。但是,您根本没有定义 GET /admin/contact 路由,这就是您得到 404 的原因。
-
对不起,我不明白。你能给我看一些例子吗?谢谢。