使用Slim PHP的默认GET路由 [英] Default GET route with Slim PHP

查看:171
本文介绍了使用Slim PHP的默认GET路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用Slim PHP框架构建了一个小型API,它工作得很好。然而,我想为根/设置一个GET路由,它以基本消息作出响应,并让其他GET请求返回拒绝访问。

阅读文档和各种示例后,我一直无法弄清楚如何完成这些任务。我的项目只依靠POST路由,但能够响应针对根域和任何其他页面的GET请求将会非常棒。



代码:

  // SLIM INSTANCE 
$ app = new \Slim\Slim();
$ app-> contentType('application / json');
$ b // SLIM ROUTES
$ app-> group('/ core',function()use($ app)
{
$ app-> post('/ create','Create');
$ app-> post('/ start','Start');
$ app-> post('/ stop','停止');
$ app->后('/ delete','删除');
});


解决方案

如果您想响应不同的方法, map() -Method:

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

注册一个'默认路由',如果路由不匹配,您可以覆盖'notFound'处理程序:

$ $ $ $ $ app $ gt; notFound(function()use($ app) {
$ app-> response-> setStatus(403);
//输出'拒绝访问',重定向到登录页面或任何你想要做的事情
});

完成一个'root'路由: $ app-> get ('/',function(){/*...*/}); 应该是这个。


I've recently built a small API using the Slim PHP framework and it is working great. 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".

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.

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:

$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:

$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(){/*...*/}); should to exactly this.

这篇关于使用Slim PHP的默认GET路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆