3. Homesteadを用いたsymfony4環境構築手順(Entity&テーブル作成編)
DBの環境を整えたらMVCのModelとなるものを作成していく。 symfony4では(一般的にもですが)これをEntitiyと呼ぶ。下記の動画を参考にしEntityとテーブル作成を行った。
Symfony 4 : Authentication (Login page)
概要
今回はUserテーブルを作成する。Laravelだとphp artisan make:auth
でかなりしっかりとしたログイン画面が出来る。symfonyはこの辺りが無い?
1. Entityの作成
vagrant@homestead:~/code$ php bin/console make:entity
上記コマンドを入力すると、対話形式でEntityの作成が行われる。
今回は下記のような設定とした。作成されたファイルはscr\Entity\User.php
に配置される。
vagrant@homestead:~/code$ php bin/console make:entity Class name of the entity to create or update (e.g. DeliciousChef): > User created: src/Entity/User.php created: src/Repository/UserRepository.php Entity generated! Now let's add some fields! You can always add more fields later manually or by re-running this command. New property name (press <return> to stop adding fields): > username Field type (enter ? to see all types) [string]: > Field length [255]: > Can this field be null in the database (nullable) (yes/no) [no]: > updated: src/Entity/User.php Add another property? Enter the property name (or press <return> to stop adding fields): > password Field type (enter ? to see all types) [string]: > Field length [255]: > Can this field be null in the database (nullable) (yes/no) [no]: > updated: src/Entity/User.php Add another property? Enter the property name (or press <return> to stop adding fields): > email Field type (enter ? to see all types) [string]: > Field length [255]: > Can this field be null in the database (nullable) (yes/no) [no]: > updated: src/Entity/User.php Add another property? Enter the property name (or press <return> to stop adding fields): > Success! Next: When you're ready, create a migration with make:migration
2. Entityの定義
Entityのファイルを開き、必要なカラムを定義していく。デフォルトではidだけが定義されている。このEntity定義を基にテーブルが作成される。
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; /** * @ORM\Entity(repositoryClass="App\Repository\UserRepository") */ class User implements UserInterface { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255, unique=true) */ private $username; ...
3. テーブル作成(マイグレーションの実施)
下記のコマンドでEnity定義を基にしたマイグレーションを実施する。 コマンド後はマイグレーションファイルとテーブルが作成されている。
//マイグレーションファイルの作成 php bin/console doctrine:migrations:diff //テーブルの作成 php bin/console doctrine:migrations:migrate