LoginSignup
3
3

More than 3 years have passed since last update.

Homestead で始める Symfony 5

Posted at

Symfony の公式ドキュメント および Homestead の公式ドキュメント (日本語訳) を参考にして Homestead での Symfony 5.0 の始め方を解説する。

Laravel Homestead (logo)

確認環境

  • macOS Catalina 10.15.4
    • bash 3.2.57
    • Homebrew 2.2.17
    • Git 2.26.2
    • VirtualBox 6.1.8
    • Vagrant 2.2.9
    • vagrant-vbguest 0.24.0
    • vagrant-hostsupdater 1.1.1.160
  • Homestead 10.8.0
    • Homestead Vagrant Box 9.5.1
    • Ubuntu 18.04.4
    • nginx 1.15.8
    • MySQL 5.7.29
    • PHP 7.4.5
    • Composer 1.10.6
  • Symfony 5.0.8
  • Symfony CLI 4.15.0

ローカルマシン環境構築

Homebrew のインストール
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Homebrew は macOS 用パッケージマネージャー。

Git / VirtualBox / Vagrant のインストール
brew cask install git virtualbox virtualbox-extension-pack vagrant

Oracle VM VirtualBox は仮想化ソフトウェアのひとつ。 Vagrant の利用に必要。

Vagrant は単一のワークフローで仮想マシン環境を構築および管理するためのツール。 1

vagrant-vbguest / vagrant-hostsupdater プラグインのインストール
vagrant plugin install vagrant-vbguest vagrant-hostsupdater

vagrant-vbguest は GuestAdditions のバージョンがホスト OS とゲスト OS 間で相違があった場合に自動更新する Vagrant プラグイン。

vagrant-hostsupdater は /etc/hosts を自動更新する Vagrant プラグイン。

[homestead] GuestAdditions versions on your host (6.1.8) and guest (6.0.0) do not match.

SSH 認証鍵の生成
cat ~/.ssh/id_ed25519_homestead || \
ssh-keygen \
 -C "joe@example.com $(date +'%Y-%M-%dT%T%z')" \
 -f ~/.ssh/id_ed25519_homestead \
 -N '' \
 -t ed25519

実行結果
cat: /Users/Joe/.ssh/id_ed25519_homestead: No such file or directory
Generating public/private ed25519 key pair.
Your identification has been saved in /Users/Joe/.ssh/id_ed25519_homestead.
Your public key has been saved in /Users/Joe/.ssh/id_ed25519_homestead.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX joe@example.com 1970-01-01T00:00:00+0900
The key's randomart image is:
+--[ED25519 256]--+
|  .ooo++ +.      |
|  o.+++o*o       |
|  .oo+ o=.o      |
| o o...= . B o   |
|. o . = S o X .  |
| . o   .   E +   |
|. . .       .    |
|.* +             |
|ooB..            |
+----[SHA256]-----+

必須ではないが、新たに生成する方が望ましい。
Ed25519 の方が RSA よりも暗号強度が高く、公開鍵サイズが小さい。また検証時間も遅くない。

Homestead Vagrant Box の追加

vagrant box add laravel/homestead

実行結果
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homestead
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) hyperv
2) parallels
3) virtualbox
4) vmware_desktop

Enter your choice: 3
==> box: Adding box 'laravel/homestead' (v9.5.1) for provider: virtualbox
    box: Downloading: https://vagrantcloud.com/laravel/boxes/homestead/versions/9.5.1/providers/virtualbox.box
Download redirected to host: vagrantcloud-files-production.s3.amazonaws.com
    box: Calculating and comparing box checksum...
==> box: Successfully added box 'laravel/homestead' (v9.5.1) for 'virtualbox'!

Homestead のダウンロード

git clone https://github.com/laravel/homestead.git ~/Homestead

実行結果
Cloning into '/Users/Joe/Homestead'...
remote: Enumerating objects: 76, done.
remote: Counting objects: 100% (76/76), done.
remote: Compressing objects: 100% (54/54), done.
remote: Total 4488 (delta 43), reused 51 (delta 21), pack-reused 4412
Receiving objects: 100% (4488/4488), 1.01 MiB | 1.16 MiB/s, done.
Resolving deltas: 100% (2740/2740), done.

release ブランチのチェックアウト
git checkout release &&
git branch &&
git pull
Branch 'release' set up to track remote branch 'release' from 'origin'.
Switched to a new branch 'release'
  master
* release
Already up to date.
Homestead の初期化
cd Homestead
bash init.sh
Homestead initialized!
Homestead.yaml の編集
IP='192.168.10.10' &&
KEY_NAME='id_ed25519_homestead' &&
HOST_PATH='\~/Projects' &&
GUEST_PATH='projects' &&
PROJECT_NAME='symfony' &&
SITE_HOSTNAME='symfony.test' &&
sed \
 -e '/vagrant\/code$/a\
    \      type: "nfs"' \
 -e '/code\/public/a\
    \      type: "symfony4"' \
 -e "s|192.168.10.10|${IP}|" \
 -e "s|id_rsa|${KEY_NAME}|" \
 -e "s|\~/code|${HOST_PATH}|" \
 -e "/vagrant\/code$/ s|code|${GUEST_PATH}|" \
 -e "s|homestead.test|${SITE_HOSTNAME}|" \
 -e "/public/ s|code|${GUEST_PATH}/${PROJECT_NAME}|" \
 -e '/^#/d' \
 -i '' \
 Homestead.yaml
ip:

ip: には 192.168.10.10 がデフォルトで指定されている。

authorize:

authorize: には公開鍵ファイルとして ~/.ssh/id_rsa.pub がデフォルトで指定されている。

keys:

keys: には秘密鍵ファイルとして ~/.ssh/id_rsa がデフォルトで指定されている。

folders:

map: はホスト OS (macOS) 側のパス。
to: はゲスト OS (Vagrant) 側のパス。
type:nfs を指定すると NFS が有効化される。 rsyncsmb を指定することもできる。

sites:

map: はゲスト OS (Vagrant) 側のホスト名。
to: はゲスト OS (Vagrant) 側の公開ディレクトリ。
type: はデフォルトの laravel 以外に symfony4symfony2 などが指定できる。 2

features:

オプションのソフトウェアのインストールを指定できる。

sed

macOS の BSD 系 sed コマンドは GNU 系と異なり、バックアップファイル作成指定の -i オプションに0バイトを指定することで上書き保存になる。
値が未指定の場合は undefined labelextra characters などのエラーメッセージが出力される。

Vagrant の実行
vagrant up

実行結果
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Importing base box 'laravel/homestead'...
==> homestead: Matching MAC address for NAT networking...
==> homestead: Checking if box 'laravel/homestead' version '9.5.1' is up to date...
==> homestead: Setting the name of the VM: homestead
==> homestead: Clearing any previously set network interfaces...
==> homestead: Preparing network interfaces based on configuration...
    homestead: Adapter 1: nat
    homestead: Adapter 2: hostonly
==> homestead: Forwarding ports...
    homestead: 80 (guest) => 8000 (host) (adapter 1)
    homestead: 443 (guest) => 44300 (host) (adapter 1)
    homestead: 3306 (guest) => 33060 (host) (adapter 1)
    homestead: 4040 (guest) => 4040 (host) (adapter 1)
    homestead: 5432 (guest) => 54320 (host) (adapter 1)
    homestead: 8025 (guest) => 8025 (host) (adapter 1)
    homestead: 9600 (guest) => 9600 (host) (adapter 1)
    homestead: 27017 (guest) => 27017 (host) (adapter 1)
    homestead: 22 (guest) => 2222 (host) (adapter 1)
==> homestead: Running 'pre-boot' VM customizations...
==> homestead: Booting VM...
==> homestead: Waiting for machine to boot. This may take a few minutes...
    homestead: SSH address: 127.0.0.1:2222
    homestead: SSH username: vagrant
    homestead: SSH auth method: private key
    homestead: Warning: Connection reset. Retrying...
    homestead: Warning: Remote connection disconnect. Retrying...
    homestead:
    homestead: Vagrant insecure key detected. Vagrant will automatically replace
    homestead: this with a newly generated keypair for better security.
    homestead:
    homestead: Inserting generated public key within guest...
    homestead: Removing insecure key from the guest if it's present...
    homestead: Key inserted! Disconnecting and reconnecting using new SSH key...
==> homestead: Machine booted and ready!
[homestead] GuestAdditions versions on your host (6.1.8) and guest (6.0.0) do not match.
Reading package lists...
Building dependency tree...
Reading state information...
dkms is already the newest version (2.3-3ubuntu9.7).
linux-headers-4.15.0-96-generic is already the newest version (4.15.0-96.97).
linux-headers-4.15.0-96-generic set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Copy iso file /Applications/VirtualBox.app/Contents/MacOS/VBoxGuestAdditions.iso into the box /tmp/VBoxGuestAdditions.iso
Mounting Virtualbox Guest Additions ISO to: /mnt
mount: /mnt: WARNING: device write-protected, mounted read-only.
Installing Virtualbox Guest Additions 6.1.8 - guest version is 6.0.0
Verifying archive integrity... All good.
Uncompressing VirtualBox 6.1.8 Guest Additions for Linux........
VirtualBox Guest Additions installer
Removing installed version 6.0.0 of VirtualBox Guest Additions...
update-initramfs: Generating /boot/initrd.img-4.15.0-96-generic
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Starting.
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel
modules.  This may take a while.
VirtualBox Guest Additions: To build modules for other installed kernels, run
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup <version>
VirtualBox Guest Additions: or
VirtualBox Guest Additions:   /sbin/rcvboxadd quicksetup all
VirtualBox Guest Additions: Building the modules for kernel 4.15.0-96-generic.
update-initramfs: Generating /boot/initrd.img-4.15.0-96-generic
VirtualBox Guest Additions: Running kernel modules will not be replaced until
the system is restarted
An error occurred during installation of VirtualBox Guest Additions 6.1.8. Some functionality may not work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
Unmounting Virtualbox Guest Additions ISO from: /mnt
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.0
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
Got different reports about installed GuestAdditions version:
Virtualbox on your host claims:   6.0.0
VBoxService inside the vm claims: 6.1.8
Going on, assuming VBoxService is correct...
==> homestead: Checking for guest additions in VM...
==> homestead: Setting hostname...
==> homestead: Configuring and enabling network interfaces...
==> homestead: Mounting shared folders...
    homestead: /vagrant => /Users/Joe/Homestead
==> homestead: Running provisioner: file...
    homestead: /Users/Joe/Homestead/aliases => /tmp/bash_aliases
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead:
    homestead: ssh-ed25519 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX joe@example.com 2020-12-20T02:12:17+0900
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Unable to mount one of your folders. Please check your folders in Homestead.yaml
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: mariadb because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: ohmyzsh because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
    homestead: Ignoring feature: webdriver because it is set to false
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/0d/xxxxxxxxxxxxxx_xxxxxxxxxxxxxxx/T/vagrant-shell19700101-00000-14bvnz6.sh
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/0d/xxxxxxxxxxxxxx_xxxxxxxxxxxxxxx/T/vagrant-shell19700101-00000-rud91r.sh
==> homestead: Running provisioner: Creating Certificate: symfony.test (shell)...
    homestead: Running: script: Creating Certificate: symfony.test
    homestead: Updating certificates in /etc/ssl/certs...
    homestead: 1 added, 0 removed; done.
    homestead: Running hooks in /etc/ca-certificates/update.d...
    homestead: done.
==> homestead: Running provisioner: Creating Site: symfony.test (shell)...
    homestead: Running: script: Creating Site: symfony.test
==> homestead: Running provisioner: shell...
    homestead: Running: inline script
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/0d/xxxxxxxxxxxxxx_xxxxxxxxxxxxxxx/T/vagrant-shell19700101-00000-1ucptug.sh
==> homestead: Running provisioner: Checking for old Schedule (shell)...
    homestead: Running: script: Checking for old Schedule
==> homestead: Running provisioner: Clear Variables (shell)...
    homestead: Running: script: Clear Variables
==> homestead: Running provisioner: Restarting Cron (shell)...
    homestead: Running: script: Restarting Cron
==> homestead: Running provisioner: Restart Webserver (shell)...
    homestead: Running: script: Restart Webserver
==> homestead: Running provisioner: Creating MySQL Database: homestead (shell)...
    homestead: Running: script: Creating MySQL Database: homestead
==> homestead: Running provisioner: Creating Postgres Database: homestead (shell)...
    homestead: Running: script: Creating Postgres Database: homestead
==> homestead: Running provisioner: Update Composer (shell)...
    homestead: Running: script: Update Composer
    homestead: Updating to version 1.10.6 (stable channel).
    homestead:
    homestead: Use composer self-update --rollback to return to version 1.10.5
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/0d/xxxxxxxxxxxxxx_xxxxxxxxxxxxxxx/T/vagrant-shell20200520-15937-bwlbbu.sh
==> homestead: Running provisioner: Update motd (shell)...
    homestead: Running: script: Update motd
==> homestead: Running provisioner: shell...
    homestead: Running: /var/folders/0d/xxxxxxxxxxxxxx_xxxxxxxxxxxxxxx/T/vagrant-shell20200520-15937-ss2ac1.sh

NFS の確認

プロセスの確認
pgrep -fl nfs
27920 /sbin/nfsd
launchd の確認
sudo launchctl list | grep nfs
27920   0   com.apple.nfsd
-   0   com.apple.nfsconf
マウントの確認
cat /etc/exports
# VAGRANT-BEGIN: 501 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
"/System/Volumes/Data/Users/Joe/Projects" -alldirs -mapall=501:20 192.168.10.10
# VAGRANT-END: 501 xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
showmount -e localhost
Exports list on localhost:
/System/Volumes/Data/Users/Joe/Projects 192.168.10.10

仮想マシンへのログイン

vagrant ssh

実行結果
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-96-generic x86_64)

Thanks for using
 _                               _                 _
| |                             | |               | |
| |__   ___  _ __ ___   ___  ___| |_ ___  __ _  __| |
| '_ \ / _ \| '_ ` _ \ / _ \/ __| __/ _ \/ _` |/ _` |
| | | | (_) | | | | | |  __/\__ \ ||  __/ (_| | (_| |
|_| |_|\___/|_| |_| |_|\___||___/\__\___|\__,_|\__,_|

* Homestead v10.8.0
* Settler v9.5.1 (Virtualbox, Parallels, Hyper-V, VMware)

0 packages can be updated.
0 updates are security updates.


vagrant@homestead:~$

MySQL の接続情報の確認
cat ~/.my.cnf
[client]
user = homestead
password = secret
host = localhost

インストールされている MySQL に、 homestead というユーザーが secret というパスワードで登録されている。 root ユーザーは空パスワードになっている。

Symfony CLI のインストール

curl -sS https://get.symfony.com/cli/installer | bash
Symfony CLI installer

Environment check
  [*] cURL is installed
  [*] Gzip is installed
  [*] Git is installed
  [*] You architecture (amd64) is supported

Download
  Finding the latest version (platform: "linux_amd64")...
  Downloading version 4.15.0 (https://github.com/symfony/cli/releases/download/v4.15.0/symfony_linux_amd64.gz)...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   635  100   635    0     0   1567      0 --:--:-- --:--:-- --:--:--  1564
100 7297k  100 7297k    0     0  14009      0  0:08:53  0:08:53 --:--:-- 17765
  Uncompress binary...
  Making the binary executable...
  Installing the binary into your home directory...
  The binary was saved to: /home/vagrant/.symfony/bin/symfony

The Symfony CLI v4.15.0 was installed successfully!

Use it as a local file:
  /home/vagrant/.symfony/bin/symfony

Or add the following line to your shell configuration file:
  export PATH="$HOME/.symfony/bin:$PATH"

Or install it globally on your system:
  mv /home/vagrant/.symfony/bin/symfony /usr/local/bin/symfony

Then start a new shell and run 'symfony'
mv /home/vagrant/.symfony/bin/symfony /usr/local/bin/symfony

Composer 単体でもインストール可能なので必須ではない。

Symfony のインストール

symfony new --full projects/symfony

symfony コマンドでインストールする場合。

composer create-project symfony/website-skeleton projects/symfony

Composer 単体でインストールする場合。

ブラウザ参照

hosts ファイルの編集
echo '192.168.10.10 symfony.test' | sudo tee -a /etc/hosts
192.168.10.10 symfony.test

ホスト OS (macOS) 側の /etc/hosts に IP アドレスとホスト名を追記することで、ホスト OS 側のブラウザで参照可能になる。

vagrant-hostsupdater プラグインか vagrant-hostmanager プラグインをインストールしていれば自動で処理されるので書き換えは不要。

ブラウザで確認

http://symfony.test/
Welcome_to_Symfony_.png

サンプルフォームの作成

Controller の自動生成
bin/console make:controller FormController
 created: src/Controller/FormController.php
 created: templates/form/index.html.twig

  Success!

 Next: Open your new controller class and add some pages!

make:controllerm:con と省略できる。

FormController.php の編集
src/Controller/FormController.php
 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
 use Symfony\Component\Routing\Annotation\Route;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\Form\Extension\Core\Type\SubmitType;

 class FormController extends AbstractController
 {
     /**
      * @Route("/form", name="form")
      */
-     public function index()
+     public function index(Request $request)
      {
+        $form = $this->createFormBuilder()
+            ->add('name')
+            ->add('submit', SubmitType::class)
+            ->getForm();
+        $form->handleRequest($request);
+        $data = array();
+        if ($form->isSubmitted() && $form->isValid()) {
+            $data = $form->getData();
+        }
         return $this->render('form/index.html.twig', [
             'controller_name' => 'FormController',
+            'form' => $form->createView(),
+            'data' => $data,
         ]);
     }
index.html.twig の編集
templates/form/index.html.twig
     </ul>
+    {{ form(form) }}
+    {{ dump(data) }}
 </div>
 {% endblock %}

lint

bin/console lint:twig templates/form/index.html.twig
 [OK] All 1 Twig files contain valid syntax.
ルーティングの確認
bin/console debug:router

実行結果
 -------------------------- -------- -------- ------ -----------------------------------
  Name                       Method   Scheme   Host   Path
 -------------------------- -------- -------- ------ -----------------------------------
  _preview_error             ANY      ANY      ANY    /_error/{code}.{_format}
  _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_phpinfo          ANY      ANY      ANY    /_profiler/phpinfo
  _profiler_search_results   ANY      ANY      ANY    /_profiler/{token}/search/results
  _profiler_open_file        ANY      ANY      ANY    /_profiler/open
  _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
  form                       ANY      ANY      ANY    /form
 -------------------------- -------- -------- ------ -----------------------------------

ブラウザで確認

http://symfony.test/from
8bd3151e-55b9-410e-aedb-b8f5c3a82ea9.png

後始末

仮想マシンの停止
vagrant halt
==> homestead: Attempting graceful shutdown of VM...
仮想マシンの破棄
vagrant destroy
==> homestead: Forcing shutdown of VM...
==> homestead: Destroying VM and associated drives...
==> homestead: Pruning invalid NFS exports. Administrator privileges will be required...
==> homestead: [vagrant-hostsupdater] Removing hosts

  1. "Vagrant is a tool for building and managing virtual machine environments in a single workflow." - Introduction - Vagrant by HashiCorp 

  2. "The available site types are: apache, apigility, expressive, laravel (the default), proxy, silverstripe, statamic, symfony2, symfony4, and zf." - Site Types - Adding Additional Sites - Laravel Homestead - Laravel - The PHP Framework For Web Artisans 

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