简体   繁体   English

使用Slim PHP的默认GET路由

[英]Default GET route with Slim PHP

I've recently built a small API using the Slim PHP framework and it is working great. 我最近使用Slim PHP框架构建了一个小API,它运行良好。 I would however like to set a GET route for the root "/" which responds with a basic message and have any other GET requests return an "access denied". 但是,我想为根“/”设置一个GET路由,该路由响应一条基本消息,并让任何其他GET请求返回“拒绝访问”。

Upon reading both the documentation and various examples, I have not been able to figure out how to accomplish either of these tasks. 在阅读文档和各种示例后,我无法弄清楚如何完成这些任务。 My project only relies on POST routes but being able to respond to GET requests aimed at both the root domain and any other pages would be fantastic. 我的项目只依赖于POST路由,但是能够响应针对根域和任何其他页面的GET请求将是非常棒的。

Code: 码:

// SLIM INSTANCE
$app = new \Slim\Slim();
$app->contentType('application/json');

// SLIM ROUTES
$app->group('/core', function() use ($app)
{
    $app->post( '/create', 'Create' );
    $app->post( '/start', 'Start' );
    $app->post( '/stop', 'Stop' );
    $app->post( '/delete', 'Delete' );
});

if you want to respond to different methods, just use the map() -Method: 如果你想回应不同的方法,只需使用map() Method:

$app->map('/create', 'Create')->via('GET', 'POST');

To register a 'default route', which will always reply with 'access denied' if no route matched, you can override the 'notFound'-Handler: 要注册“默认路由”,如果没有路由匹配,它将始终以“拒绝访问”回复,您可以覆盖'notFound'处理程序:

$app->notFound(function () use ($app) {
    $app->response->setStatus(403);
    //output 'access denied', redirect to login page or whatever you want to do.
});

To accomplish a 'root'-route: $app->get('/',function(){/*...*/}); 要完成'根'路线: $app->get('/',function(){/*...*/}); should to exactly this. 应该这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM