こんにちわ!@mrtryです。
最近、寒くなってきましたね。
最近は、ねとめしの「肉まんスープ」で温まっています。
すりごまとラー油をたくさん入れるのが好きです。
さて、「Symfony2入門」の4回目の記事です。
前回はルータについて説明しました。
今回は、コントローラについて説明します。
コントローラも理解すれば、Symfonyの基本はおさえた!と思って良いのではないでしょうか。
以下、今回の記事の目次になります。
コントローラとは
コントローラとは、Requestオブジェクトから読み取った情報を元に、Responseオブジェクトを生成して返す処理のことを指します。
Responseオブジェクトは、HTTPのResponseに相当するのもので、レンダリングされたページやリダイレクト、画像などwebにアクセスして取得できる情報を任意に返すことができます。
フレームワークでの立ち位置については、以前書いた記事「Symfony2での処理の流れについてまとめた」を見ていただければ、と思います!
コントローラの生成方法
コントローラを作成する際は、基本的にapp/console
に組み込まれている生成コマンドを利用して生成します。
今回は、実際に生成コマンドを利用して、symfonyのデモアプリケーションにコントローラを生成してみます。
デモアプリケーションのルートディレクトリにて、次のコマンドを実行してみましょう。
$ php bin/console generate:controller
実行すると、コントローラ生成に必要な項目を対話式で入力していくようになります。
以下は、実際にAppBundle
の中にDemoController
を生成し、その中にindexAction
を定義したときのログになります。
$ php bin/console generate:controller
Welcome to the Symfony2 controller generator
Every page, and even sections of a page, are rendered by a controller.
This command helps you generate them easily.
First, you need to give the controller name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post
Controller name: AppBundle:Demo
Determine the format to use for the routing.
Routing format (php, xml, yml, annotation) [annotation]:
Determine the format to use for templating.
Template format (twig, php) [twig]:
Instead of starting with a blank controller, you can add some actions now. An action
is a PHP function or method that executes, for example, when a given route is matched.
Actions should be suffixed by Action.
New action name (press <return> to stop adding actions): indexAction
Action route [/index]:
Template name (optional) [AppBundle:Demo:index.html.twig]:
New action name (press <return> to stop adding actions):
Summary before generation
You are going to generate a "AppBundle:Demo" controller
using the "annotation" format for the routing and the "twig" format
for templating
Do you confirm generation [yes]?
Controller generation
Generating the bundle code: OK
Everything is OK! Now get to work :).
対話形式で入力する項目について
ログを見つつ、入力する項目について説明します。
実際に入力した項目は、以下の6項目です。
- Controller name:
- Routing format (php, xml, yml, annotation) [annotation]:
- Template format (twig, php) [twig]:
- New action name (press to stop adding actions):
- Action route [/index]:
- Template name (optional) [AppBundle:Demo:index.html.twig]:
Controller name:
コントローラを作成するバンドル先とコントローラクラス名を指定します。
アクション名を除いた論理コントローラ名で指定します。
今回は、AppBundle
にDemoController
を作成したかったので、
AppBundle:Demo
と入力しました。
Routing format (php, xml, yml, annotation) [annotation]:
ルーティングの設定フォーマットを指定します。
デフォルトでは、annotationが指定されています。
今回は、annotation
を利用したかったので、そのままEnterで進めました。
Template format (twig, php) [twig]:
ビューで利用するテンプレートのフォーマットを指定します。
デフォルトではtwigが指定されています。
今回は、twig
を利用するので、そのままEnterで進めました。
New action name (press to stop adding actions):
アクション名を指定します。
アクションとは、コントローラークラス内に定義されるコントローラの役割を持ったメソッドのことを指します。
xxxAction
と入力すると、入力した命名でController name:
で設定したコントローラクラスにアクションが定義されます。
今回は、indexAction
という名前でActionを作成したかったので、indexAction
と入力しました。
Action route [/index]:
設定したActionのマッチするルートを設定します。
デフォルトでは、Action名からAction
を除いた文字列がルート名になります。
今回は/index
にマッチさせたかったので、そのままEnterで進めました。
Template name (optional) [AppBundle:Demo:index.html.twig]:
ビューのテンプレートの名前を指定します。
デフォルトでは論理コントローラ名の末尾にテンプレートフォーマットが追記されたものが、テンプレート名になります。
変更する必要も特になかったので、そのままEnterで進めました。
生成したコントローラの確認
一通り入力が済むと、AppBundle
にDemoController
が生成されていることを確認できます。
$ ls src/AppBundle/Controller
Admin BlogController.php DemoController.php SecurityController.php
DemoControllerを見てみます。
ルーティングが/index
にマッチするようにAnnotationで設定され、
indexAction
が定義されていることを確認できます。
$ cat src/AppBundle/Controller/DemoController.php
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DemoController extends Controller
{
/**
* @Route("/index")
*/
public function indexAction()
{
return $this->render('AppBundle:Demo:index.html.twig', array(
// ...
));
}
}
処理は特に自身で定義していませんが、render()
メソッドを用いて、
src/AppBundle/Resources/views/Demo/index.html.twig
をレンダリングし、
Responseオブジェクトとして返す処理を書かれています。
参照するviewを指定するときは、論理コントローラに似た記述で
バンドル名:コントローラクラス名:ビューファイル名
と記述すると、
src/バンドル名/Resources/views/コントローラクラス名/ビューファイル名
を参照することができます。
ルーティングの確認
consoleでdebug:route
すると、下から4番目にルーティングに登録されていることが確認できます。
ルーティング名は、指定しなければ論理コントローラ名の:
を_
に置換したものがルーティング名になります。
$ bin/console debug:route
-------------------------- ---------- -------- ------ ----------------------------------------
Name Method Scheme Host Path
-------------------------- ---------- -------- ------ ----------------------------------------
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_info ANY ANY ANY /_profiler/info/{about}
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
_twig_error_test ANY ANY ANY /{_locale}/_error/{code}.{_format}
admin_index GET ANY ANY /{_locale}/admin/post/
admin_post_index GET ANY ANY /{_locale}/admin/post/
admin_post_new GET|POST ANY ANY /{_locale}/admin/post/new
admin_post_show GET ANY ANY /{_locale}/admin/post/{id}
admin_post_edit GET|POST ANY ANY /{_locale}/admin/post/{id}/edit
admin_post_delete DELETE ANY ANY /{_locale}/admin/post/{id}
blog_index GET ANY ANY /{_locale}/blog/
blog_index_paginated GET ANY ANY /{_locale}/blog/page/{page}
blog_post GET ANY ANY /{_locale}/blog/posts/{slug}
comment_new POST ANY ANY /{_locale}/blog/comment/{postSlug}/new
app_demo_index ANY ANY ANY /{_locale}/index
security_login ANY ANY ANY /{_locale}/login
security_logout ANY ANY ANY /{_locale}/logout
homepage ANY ANY ANY /{_locale}
-------------------------- ---------- -------- ------ ----------------------------------------
補足ですが、Pathの頭に/{_locale}がついているのは、app/config/routing.ymlにprefixが設定されているからです。
app/config/routing.yml (7行目~ )
app:
resource: '@AppBundle/Controller/'
type: annotation
prefix: /{_locale}
requirements:
_locale: '%app_locales%'
defaults:
_locale: '%locale%'
ページの確認
/ja/index
へアクセスしてみると、Welcome to the Demo:index page
と表示されます。
おわりに
今回は、コントローラの役割についての紹介とコマンドを用いたコントローラ生成について紹介しました。
次回は、引き続いてコントローラについて、Responseオブジェクトを生成する際に利用するメソッドなどを紹介したいと思います。
また、この記事は、@mrtryの勉強の一環で書いています。
お気づきの点がありましたら、コメント等でご指摘いただければ幸いです!
参考