如何在Slim Framework中对路线进行分类?
我在我的公共目录中有这些基本/前线路线
$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
。
Admin/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;
});
});
});
假设我的管理区域中有文章、联系人等模块。在每个模块中,我都有get、put、delete的路由。所以我按照Admin/index.php
中的模块对它们进行分组。但我得到的404页面没有找到,当我在我的url上请求这些模块时,例如http://{localhost}/admin/contact
,我应该在浏览器上得到list of articles
,但我得到了404。
如果我把分组的路由放在public/index.php
中,我不会有这个问题,但我不想打乱这个索引,因为随着时间的推移,我有更多的模块要添加。我更喜欢把路由分成不同的索引。
因此,是否可以将分组路由拆分到不同位置(目录)中的不同index.php中。
或者我在斯利姆不应该这样做?如果是这样,斯利姆解决这个问题的方法是什么?
在您的代码中,/admin/contact
是处理联系人的GET/PUT/DELETE
的路由组
// see here v
$app->group('/contact', function () use ($app) {}):
如果你想有一个带有这个URL段的路由,那么你应该用get
代替group
也许你可以删除admin
中的组
// API group
$app->group('/admin', function () use ($app) {
// Contact group
// $app->group('/contact', function () use ($app) {
// Get All Contacts
$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;
});
// });
});
然后您可以按照访问路线
Get All -> admin/contacts
Get One -> admin/contacts/:id
Update -> admin/contacts/:id