问题
I'm using SLIM 2.0.0
Is it possible to use ->params() with GET?
In the example below
- if I call it by POST:
curl -d "param1=hello¶m2=world" http://localhost/foo
it prints: helloworld CORRECT!! - if I call it by GET:
http://localhost/foo/hello/world
it prints: NOTHING!! <- WRONG!!
Why?
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app -> get('/foo/:param1/:param2', 'foo');
$app -> post('/foo', 'foo');
$app -> run();
function foo() {
$request = \Slim\Slim::getInstance() -> request();
echo $request -> params('param1');
echo $request -> params('param2');
}
?>
回答1:
SOLVED! In the documentation page Request Variables - Slim Framework Documentation I read this:
An HTTP request may have associated variables (not to be confused with route variables). The GET, POST, or PUT variables sent with the current HTTP request are exposed via the Slim application’s request object.
If you want to quickly fetch a request variable value without considering its type, use the request object’s params() method:
<?php
$req = $app->request();
$paramValue = $req->params('paramName');
The params() method will first search PUT variables, then POST variables, then GET variables. If no variables are found, null is returned. If you only want to search for a specific type of variable, you can use these methods instead:
<?php
// Get request object
$req = $app->request();
//GET variable
$paramValue = $req->get('paramName');
//POST variable
$paramValue = $req->post('paramName');
So:
The key line is "An HTTP request may have associated variables (not to be confused with route variables)."
http://domain.com/foo/hello/wold?name=brian
In the above URI the route variables/parameters are read from the '/foo/hello/world' portion. The request GET variables are read from the query string ('name=brian') and can be accessed by $app->request()->get('name') or $app->request()->params('name').
The request POST variables are parsed from the body of the request and can be accessed $app->request()->post('param1') or $app->request()->params('param1').
Thanks to Brian Nesbitt
来源:https://stackoverflow.com/questions/12408113/slim-framework-2-0-0-unable-to-use-params-with-get