LoginSignup
7
7

More than 5 years have passed since last update.

基本からしっかり学ぶ Symfony2入門を読んで、知らなかったことメモ

Posted at

背景

  • 基本からしっかり学ぶ Symfony2入門:書籍案内|技術評論社 を買って読んでいます
    • 現在7章の途中
  • わりとSymfony2を使っているつもりでしたが、この本を読むまで知らなかったことをメモします
    • どれもSymfonyのマニュアルに書いてあることだったのですが、書籍のほうが最初から通して読みやすいので勉強になりました
      • Symfony2初心者の方はもちろん、私みたいな知ってるつもりの人にもおすすめ

P.102 submit をフォームの要素として定義する

submit をフォームの要素として定義しておくと、1つのフォームに複数ボタンがある際にうまく扱える。

See: http://symfony.com/doc/current/book/forms.html#submitting-forms-with-multiple-buttons

P.112 リダイレクトインターセプション

PRG(Post Redirect Get)パターンを使用している場合など、
Post時の情報をデバッグするのに少し手間がかかるが、
そういう場合に下記の設定をしておくと、リダイレクトせずに1枚確認画面が挟まるので
デバッグツールバーを使用してデバッグしやすくなる。

web_profiler:
    intercept_redirects: true

See: http://symfony.com/doc/current/cookbook/email/dev_environment.html#viewing-from-the-web-debug-toolbar
See: http://symfony.com/doc/current/reference/configuration/web_profiler.html#full-default-configuration

P.116 開発時にメールの宛先を強制的に自分のメールアドレス固定にする

よくある開発時のメール誤送信による事故防止。
postfixとかのsmtpサーバレベルで対応することも考えられますが、これは手軽。

config_dev.ymlを下記の部分をコメントアウトして書き換えれば、そのアドレスにしか送られなくなる。

#swiftmailer:
#    delivery_address: me@example.com

See: http://symfony.com/doc/current/cookbook/email/dev_environment.html#sending-to-a-specified-address
See: http://symfony.com/doc/current/reference/configuration/swiftmailer.html#delivery-address

P.161 ParamConverter アノテーション

ParamConverter 自体は、リクエストパラメーターを元に、なにがしかのオブジェクトに変換する機能なのだが、組み込みの Doctrine Converter が便利。

例えば、

リクエストパラメーターに埋め込まれたidを元に、リポジトリから対応するエンティティを取得。
もしなければ、404を返し、あればそのままテンプレートに渡して表示。

なんていうよくある処理がアノテーション1行で書ける。こんな感じ。

before

/**
 * @Route("/{id}")
 * @Template
 */
public function showAction($id)
{
    $repository = $this->getDoctrine()->getRepository(Product::class);
    $product = $repository->find($id);

    if (!$product) {
        throw $this->createNotFoundException();
    }

    return [
        'product' => $product,
    ];
}

after

/**
 * @Route("/{id}")
 * @ParamConverter("product", class="AppBundle:Product")
 * @Template
 */
public function showAction(Product $product)
{
    return [
        'product' => $product,
    ];
}

See: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html

P.191 Commandからのメール送信など、リクエスト情報がない場合のURL生成

URL生成時のホスト名は、HTTPリクエストのHostヘッダなどから取るようになってるので、
CLIでメール送信などする場合にURLがlocalhostになっちゃう。
そういう場合は router.request_context.host などのパラメーターを設定すればいいらしい。

parameters:
    router.request_context.host: example.org
    router.request_context.scheme: https

See: http://symfony.com/doc/current/cookbook/console/sending_emails.html#configuring-the-request-context-globally

7
7
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
7