Wizard
Wizard

Reputation: 11265

Symfony2 storing requests in object

I'm building API with fosRest bundle.

The method where I'm stuck looks like:

public function postUser(Request $request)
{
}

I'm want handle request with User entity instead of Request, but problem if that I'm receiving params, that are not in User class, or have different names

What is best way to handle this request with custom object, and where store it ?

I want do that to have code autosuggest in IDE.

My idea is created Model User class, is enough good for that ?

Upvotes: 1

Views: 61

Answers (1)

Cameron Hurd
Cameron Hurd

Reputation: 5031

Try using the @ParamConverter annotation from SensioFrameworkExtraBundle to inject a $user param into your controller based on the request data.

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Appbundle\Entity\User;

class UserController
{
    /** 
     * @ParamConverter("user", class="AppBundle:User") 
     */
    public function postUserAction(User $user)
    {
        // ...
    }
}

(Here are the symfony docs for The SensionFrameworkExtraBundle, and specifically the @ParamConverter annotation.)

By use-ing your User class, and typehinting it in the controller param, your IDE should be able to glean more about it. Different approaches are necessary for different IDEs, of course, but this gets you to a strong starting position.

As from the docs, you might want to supply some more details about just how, exactly, the framework should try to convert a parameter into an object:

DoctrineConverter Options

A number of options are available on the @ParamConverter or (@Entity) annotation to control behavior: id: If an id option is configured and matches a route parameter, then the converter will find by the primary key. One simple id example, below:

/**
 * @Route("/blog/{post_id}")
 * @ParamConverter("post", options={"id" = "post_id"})
  */
public function showPostAction(Post $post)
{
}

Upvotes: 1

Related Questions