Restful
Restful copied to clipboard
Generating links to a crud route.
Let's say i have routes:
new CrudRoute('api/v1/users',
[
'presenter' => 'Users',
'action' => [ IResourceRouter::POST => 'create']
],
IResourceRouter::POST);
new CrudRoute('api/v1/users/<id>',
[
'presenter' => 'Users',
'action' => [ IResourceRouter::GET => 'read']
],
IResourceRouter::GET);
Now i want from Users::actionCreate return link to a newly created user.
class UsersPresenter
{
public function actionCreate()
{
$id = 3;
$this->resource->link = $this->link('read', ['id' => $id]); //This does not work.
}
public function actionRead($id)
{
}
}
Is there a way to generate links to crud routes?
Try $this->resource->link = $this->link('Users:', ['id' => $id]);)
@kuzmamar It's probably not connected to the problem, but why are you using CrudRoute instead of ResourceRoute? CrudRoute is a shorcut to have definition for ALL CRUD in 1 route. If you're defining your own action names mapped to the HTTP methods, you should use ResourceRoute instead (now it works, because you're using the same naming convention for the POST method - create
, but once you use another name, it won't work because CrudRoute will replace your HTTP to ACTION definition).
@vnenkpet yep that works. But what if I wanted link to a relation. From example:
$router[] = new ResourceRoute('api/v1/articles/<id>/comments[/<commentId>]', array(
'presenter' => 'Articles',
'action' => array(
IResourceRouter::GET => 'readComment',
IResourceRouter::POST => 'createComment'
)
), IResourceRouter::GET | IResourceRouter::POST);
Now from Articles::createComment:
public function createComment($id /* article id */)
{
$commentId = 1;
$this->link(/* Somehow link to readComment. */); // How to do that? $this->link('readComment', ['id' => $id, 'commentId' => $commentId]); surely does not work.
}
public function readComment($id, $commentId) {}
I do not know if it is possible with link method. @Stene3 You right. For my case ResourceRoute is probably better choice. Edit:
$this->link('Articles:', ['id' => $id, 'commentId' => $commenId]); // generates /api/v1/articles/1?commentId=3 but i want /api/v1/articles/1/comments/3
@kuzmamar I am not sure if you are still asking about CrudRoute. But with CrudRoute you can do something like
$router[] = new CrudRoute("crud/[<id>/[<relation>[/<relationId>]]]", "Model");
This way you just replace the parameters and you can also get the routes for multiple relations.
$this->link('Model:', ['id' => 1, 'relation' => 'comment', 'relationId' => 1]);
@vnenkpet Thanks! That solved my problem. :+1:
@kuzmamar Can you keep this issue opened, please? Although there's a way how to use it, I'm still thinking it's an issue :) Thanks
@Stene3 ok :)