Somfonyシェル画面にログインする
$ php app/console --shell
別に入らなくても良いのですが、こっちの方が入力するコマンド量が少なくて楽です。
controllerを新規作成する
シェル画面に入っている場合はgenerate:controller
、そうじゃない場合はphp app/console generate:controller
で対話画面が起動します。
-
Controller name
で作成するコントローラー名(バンドル名:コントローラー名) -
Routing format
でルーティングのフォーマットを指定します -
Template format
でviewのフォーマットを指定します -
New action name
はアクションの名前入れるっぽいですが、今回はスキップしてます
Symfony > 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:Concert
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):
作成前の確認
入力した値の確認画面が出てくるので、確認してからenterかyesを入力します。
Summary before generation
You are going to generate a "AppBundle:Concert" controller
using the "annotation" format for the routing and the "twig" format
for templating
Do you confirm generation [yes]?
以下のようなメッセージが出たらOKです。
Controller generation
Generating the bundle code: OK
You can now start using the generated code!
コントローラーにパスを設定する
作成したコントローラーsrc/XXXBundle/Controller/YOURController.php
を以下のようにします。
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class ConcertController extends Controller
{
/**
* @Route("/page/")
**/
public function indexAction()
{
$information
return $this->render('Page/index.html.twig');
}
}
アノテーションの@Route("/page/")
でパスを指定し、$this->render('Page/index.html.twig')
でviewのテンプレートを指定します。
viewを設定する
app/Resources/views/Page/index.html.twig
にHTMLを書き込みます。
<html>
<body>
<h1>Hello Website</h1>
</body>
</html>
動作確認
server:start 127.0.0.1:8000
もしくはphp app/console server:start 127.0.0.1:8000
すると、PHPのビルトインサーバーが起動します。
localhost:8000/page
でアクセスすると、ページが表示される(はず)です。
注意点
Controller名はXXXBundle:コントローラー名
にする
generateする時に怒られるだけなので、致命的な問題は出ませんが念のため。
Controller name: Concert
The controller name must contain a : ("Concert" given, expecting something like AcmeBlogBundle:Post)