Question

I am sort of newbie to Slim and now I am kinda lost on how to get parameters from a RESTful request. Here is the relevant part of the code:

//.....

$app->get('/api/json(/:do(/:entity(/:arg+)))', 
        "\Slim\Controller\API:jsonAction");
// .....

# Controller


<?php
namespace Slim\Controller;

use Slim\Slim;


class API {

    public function jsonAction()
    {
        print json_encode([
            "response" => "200", 
            "body" => "JSON API called"
        ]);

        var_dump(Slim::getInstance()->request->params('do'));
        var_dump(Slim::getInstance()->request->params('entity'));
        var_dump(Slim::getInstance()->request->params('arg')[0]);
    }
}

Output, when I try http://localhost/index.php/api/json/kill/us/all:

{"response":"200","body":"JSON API called"}NULLNULL

The route is working(as expected), but I cannot reach $do, $entity, $arg[]. The expected output will be:

{"response":"200","body":"JSON API called"}killusall

I can't recall the original page at which I saw this kind of controller usage with Slim, so excuse me if the question is stupid. Thanks in advance!

Was it helpful?

Solution

According to these comments there are a couple of ways to get RESTful URI parameters. The first way of doing this is referring to this comment, #15:

#In the same controller

public function jsonAction($do = null, $entity = null, $argv = null)
{
    print json_encode([
        "response" => "200", 
        "body" => "JSON API called"
    ]);

    var_dump($do); // Output string(4) "kill"
    var_dump($entity); // Output string(2) "us"
    var_dump($arg[0]); // Output array(1) { [0]=> string(3) "all" }
}

The second approach is according to this comment, #18:

# When we define the route
$app->get('/api/json(/:do(/:entity(/:arg+)))', 
        "\Slim\Controller\API:jsonAction")->setParams(
    array($do, $entity, $arg)
); 

And the third way of doing things, which I think is a bit ugly.. Again to #15 comment:

$app->get('/hello(/:param)', 
    function ($do = NULL, $entity = NULL, $arg = NULL) use($app) {
        (new \controller\sayHello($app))->index($do, $entity, $arg);
});

So basically I am going to stick to the first approach, It is more elegant and more framework oriented(it handles it behind the scenes).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top