Default GET route with Slim PHP

白昼怎懂夜的黑 提交于 2020-01-24 08:42:26

问题


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' );
});

回答1:


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.



来源:https://stackoverflow.com/questions/32568765/default-get-route-with-slim-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!