2016-01-26 102 views
0

在這種情況下,如何獲取參數?獲取路由參數 - Slim Framework 3

$this->get('/{id}', function($request, $response, $args) { 
    return $response->withJson($this->get('singleSelect')); 
}); 

$this->appContainer['singleSelect'] = function ($id) { 
    return $this->singleSelect($id); 
}; 

public function singleSelect($id) { 
    return $id; 
} 

在此先感謝。

UPDATE

解決方案在我的情況:

$app->group('/id', function() { 
    $this->get('/{id}', function($request, $response, $args) { 
     $this['container'] = $args; //work with $args inside the container 
     return $this->singleSelect($id); 
    }); 
}); 

回答

0

如果我正確理解服務已經不能訪問路由參數。所有可以訪問的容器本身,但它可能會非常棘手從中獲得有關參數的信息(類似$container->getRoutes()['<routename>']->getArguments()其中<routename>路由器可以有子路徑等)

恕我直言,你的代碼應該是這樣的:

$container = new \Slim\Container; 
$app = new \Slim\App($container); 

class Example { 
    public function singleSelect($id) { 
     return $id; 
    } 
} 

$container['example'] = function() { 
    return new Example(); 
}; 

$app->group('/id', function() { 
    $this->get('/{id}', function($request, $response, $args) { 
     return $response->withJson($this->example->singleSelect($args['id'])); 
    }); 
}); 

$app->run(); 
+0

上面的另一個解決方案是在我的問題更新中。謝謝。 –