LoginSignup
7
3

More than 3 years have passed since last update.

Symfony4のController用アノテーションで、paramConverterとEntityを使う

Last updated at Posted at 2019-08-08

毎度忘れるので、メモ代わりに。要するに「Symfonyマニュアルの@ParamConverter」のざっくり訳になります。

ArgumentResolverを利用する方法もあります→アクション引数でログインしているユーザーの情報を取得する

便利なアノテーション

SymfonyのControllerで使えるアノテーションに@ParamConverter@Entityというのがあって、便利だなと言う話。

自動でエンティティに変換する

Symfonyの便利な機能に、ルートをアノテーション(@Route)で指定できます。

use Symfony\Component\Routing\Annotation\Route;

class PostController 
{
    /**
     * @Route("blog/{id}", name="post-info")
     * @param Post $post
     */
    public function show(Post $post) {...}

さらに便利なことに、{$id}をプライマリキーとして使って、$postを渡してくれます。条件は、

  • ルートの中に{id}が存在すること。これがプライマリキーになります。
  • 引数にエンティティが存在すること。

複数のエンティティがある場合

次はPostCommentの複数のエンティティをアノテーションで取得する方法です。これには@Entityアノテーションを利用して、2つめのエンティティの変換方法を指定します。

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use Symfony\Component\Routing\Annotation\Route;

class PostCommentController 
{
    /**
     * @Route("/blog/{id}/comments/{comment_id}")
     * @Entity("comment", expr="repository.find(comment_id)")
     * 
     * @param Post $post
     * @param Comment $comment
     */
    public function show(Post $post , Comment $comment) {...}

@ParamConverterとは?

マニュアルのタイトルに有る@ParamConverterとは何でしょう?

最初の自動でエンティティに変換してくれる機能について、いろいろな設定をするアノテーションと理解するのが早そうです(多分、違う…)。

例えば、{id}ではなかったり、プライマリキーではなかったり、とかでしょうか。

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

毎回のように間違えるのは、複数のエンティティに変換している場合に@ParamConverterを使おうとしても、動かないことです。この場合は@Entityアノテーションを利用することになります。

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3