Symfony2のapp/console エンティティ周り

// データベース作成・削除
php app/console doctrine:database:drop --force
php app/console doctrine:database:create

// バンドルの作成
php app/console generate:bundle --namespace="My/ProjectBundle" --format=yml

// エンティティの作成 --fieldsオプションも付けられます
php app/console doctrine:generate:entity --entity=MyProjectBundle:Post --format=yml

// yml Entityからモデルを作成 --no-backupでバックアップを作成しない
php app/console doctrine:generate:entities "MyProjectBundle" --no-backup

// エンティティからテーブルの作成・更新
php app/console doctrine:schema:create
php app/console doctrine:schema:update --force

ymlエンティティ作成に関してfieldsの詳細は
http://symfony.com/doc/2.0/reference/forms/types.html

relationsなどに関して
http://stackoverflow.com/questions/7546377/problem-with-symfony2-schema-yaml-unable-to-get-relationships-working

Symfony2チュートリアル CRUDアプリを作る



Symfony2でひとまず動かすためのチュートリアルです。
crudコマンドを使って簡単なCRUDを実装します。

http://yourhost/app_dev.php/post/
チュートリアル用のアプリケーションを作ることを前提にします。

バンドル・エンティティを作成

TutorialHelloバンドルを作成し、Postというエンティティを追加します。

$ php app/console generate:bundle --namespace=Tutorial/HelloBundle
$ php app/console doctrine:generate:entity --entity=TutorialHelloBundle:Post --format=yml

Postエンティティの編集

doctrine:generate:entity --entity=TutorialHelloBundle:Post --format=yml
では2つのファイルが作成されます。

src/Tutorial/HelloBundle/Entity/Post.php
src/Tutorial/HelloBundle/Resources/config/doctrine/Post.orm.yml

一つはPostモデル、Post.orm.ymlはDoctrineORマッパー用(今回はアノテーションを利用しません)。
Post.orm.ymlを編集し、 app/console doctrine:generate:entitiesを実行
することでモデルを生成します。

Post.orm.ymlにnameとsubject, descriptionのカラムを準備します。

$ vim src/TutorialHelloBundle/Resources/config/doctrine/Post.orm.yml
Tutorial\HelloBundle\Entity\Post:
  type: entity
  table: null
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    name:
      type: string
      notnull: true
    subject:
      type: string
      notnull: true
    description:
      type: text
      notnull: true
    
  lifecycleCallbacks: {  }

ORM.YMLからモデル生成しテーブルをupdate

編集したPost.orm.ymlからPost.phpモデルを作成し、doctrine:schema:updateで
テーブルと同期させます。テーブルが存在しない場合は doctrine:schema:create
doctrine:generate:entitiesでバックアップを作成したくない場合は

    • no-backupオプションをつけます。バックアップを作成します。

Post.php~ というファイルが自動的に作成されます。

$ php app/console doctrine:generate:entities TutorialHelloBundle
$ php app/console doctrine:schema:update --force

PostクラスのCRUDを作成

doctrine:generate:crudCRUDを作成します。--entityオプションは必ず必要です。
また、--with-writeをつけないと表示のみ(show)となります。
CRUDには--with-writeが必要です。

$ php app/console doctrine:generate:crud --entity=TutorialHelloBundle:Post --with-write

routingの編集

CRUDのファイルが生成されたらroutingしてあげましょう。
app_dev.phpから/postからアクセスするように設定します。
app/config/routing_dev.yml を編集します。

$vim app/config/routing_dev.yml
# app/config/routing_dev.yml
_post:
    resource: "@TutorialHelloBundle/Controller/PostController.php"
    type:     annotation
    prefix:   /post

これで
http://yourhost/app_dev.php/post
にアクセスできるようになると思います。

Symfony2でも思った以上に簡単にCRUDアプリケーションが出来上がります。