もがき系プログラマの日常

もがき系エンジニアの勉強したこと、日常のこと、気になっている技術、備忘録などを紹介するブログです。

Symfony5を試してみた

はじめに

こんにちは。

この記事はSymfony Advent Calendar 2019 24日目の記事です。

昨日は@ringtail003さんのSymfony4+ で Server-Sent events を使ってみようでした。

直近ではLaravelを触っており、SymfonyはAdvent Calendarを書くときだけ触っています。

なので1年ぶりなので完全に忘れています。

ちなみに去年のAdvent CalendarはSymfony4でNelmioApiDocBundleを試してみたという記事を書いています。

今回は先月Symfony5がリリースされたので、インストールして試してみようと思います。

こちらの記事をみるに、新規機能はなく不具合の修正が中心とのことです。

なので、今回やることはSymfony4でも再現できるものだと思います。

では早速始めます。

参考サイト

本題

インストール

以下のコマンドでインストールしてみます。

$ composer create-project symfony/website-skeleton sample_project
$ ./bin/console -V
Symfony 5.0.2 (env: dev, debug: true)

5.0.2入りました。

参考サイトで紹介されている通り、ローカルサーバを立てる用のコマンドを入れたいのでインストールします。

$ composer req server

[InvalidArgumentException]                                                    
Could not find package symfony/web-server-bundle in a version matching 5.0.*  

5系ではまだ使えないようでした...

しょうがないのでphpコマンドで行きます。

$ php -S localhost:8080 -t public
PHP 7.3.8 Development Server started at Tue Dec 24 01:14:16 2019
Listening on http://localhost:8080
Document root is /Users/yudai_fujita/projects/study/php/symfony/sample_project
Press Ctrl-C to quit.

f:id:kojirooooocks:20191224023743p:plain

入りました。

CRUD作成

試しに簡単なCRUDをつくってみます。 コマンドは以下

$ ./bin/console make:crud

ただ、Entityを先に作る必要があるので、適当に作っておきます。

$ php bin/console make:entity SampleUser

 created: src/Entity/SampleUser.php
 created: src/Repository/SampleUserRepository.php

Entityは以下です。

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\SampleUserRepository")
 */
class SampleUser
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\GeneratedValue()
     * @ORM\Column(type="string", length=128)
     */
    private $name;

    /**
     * @ORM\GeneratedValue()
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\Column(type="text")
     */
    private $description;

    public function getId(): ?int
    {
        return $this->id;
    }
}

作成したEntityからマイグレショーンファイルを作成します。

$ php bin/console doctrine:migrations:diff
Generated new migration class to "/Users/yudai_fujita/projects/study/php/symfony/sample_project/src/Migrations/Version20191223164904.php"

To run just this migration for testing purposes, you can use migrations:execute --up 20191223164904

To revert the migration you can use migrations:execute --down 20191223164904

出来たマイグレーションファイルを流し込みます。

$ php bin/console doctrine:migrations:migrate
                                                              
                    Application Migrations                    
                                                              

WARNING! You are about to execute a database migration that could result in schema changes and data loss. Are you sure you wish to continue? (y/n)y
Migrating up to 20191223164904 from 0

  ++ migrating 20191223164904

     -> CREATE TABLE sample_user (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(128) NOT NULL, email VARCHAR(255) NOT NULL, description LONGTEXT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB

  ++ migrated (took 221.3ms, used 20M memory)

  ------------------------

  ++ finished in 268.5ms
  ++ used 20M memory
  ++ 1 migrations executed
  ++ 1 sql queries
——

色々詳細が出てるのがいいなぁ。

とか思いつつ、やっとCRUD作成コマンドを実行します。

$ ./bin/console make:crud SampleUser

 created: src/Controller/SampleUserController.php
 created: src/Form/SampleUserType.php
 created: templates/sample_user/_delete_form.html.twig
 created: templates/sample_user/_form.html.twig
 created: templates/sample_user/edit.html.twig
 created: templates/sample_user/index.html.twig
 created: templates/sample_user/new.html.twig
 created: templates/sample_user/show.html.twig

           
  Success! 
           

 Next: Check your new CRUD by going to /sample/user/

出来たみたいです。 CRUD画面にアクセスしてみます。

f:id:kojirooooocks:20191224023809p:plain

出来てます!

さっそくデータを作ってみようと Create New をクリックすると

f:id:kojirooooocks:20191224023822p:plain

エラー。

Entityで用意したプロパティにSetter/Getterを追加してませんでした。。。

追加すると問題なく新規作成ができました。

修正も問題ありません。

f:id:kojirooooocks:20191224023907p:plain

EasyAdminBundle導入

せっかくなので、なんらかのBundleを入れてみようと思ったのですが、まだ5系対応されてないのが多かったです。。。 調べるとEasyAdminBundleは5系対応されていたので、入れてみました。

インストールは以下

$ composer require easycorp/easyadmin-bundle
Using version ^2.3 for easycorp/easyadmin-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "5.0.*"

Prefetching 2 packages 🎵 💨
  - Downloading (100%) 

Package operations: 2 installs, 0 updates, 0 removals
  - Installing pagerfanta/pagerfanta (v2.1.3): Loading from cache
  - Installing easycorp/easyadmin-bundle (v2.3.4): Loading from cache
Writing lock file
Generating autoload files
ocramius/package-versions: Generating version class...
ocramius/package-versions: ...done generating version class
Symfony operations: 1 recipe (c89d68f6646119e76a9f3a281a2b655c)
  - Configuring easycorp/easyadmin-bundle (>=2.0): From github.com/symfony/recipes:master
Executing script cache:clear [OK]
Executing script assets:install public [OK]

Some files may have been created or updated to configure your new packages.
Please review, edit and commit them: these files are yours.

次に、 設定ファイルを修正します。

config/packages/easy_admin.yaml

easy_admin:
    entities:
        - App\Entity\SampleUser

とりあえず最低限これで設定は終わりなので、 /admin にアクセスしてみます。

f:id:kojirooooocks:20191224024028p:plain

バッチリ入りました。

Image from Gyazo

いい感じです。

本来はもっと細かく設定ができるのですが、今回は試すだけなので一旦ここまでで。

終わりに

こんな感じの簡単なお試しブログになりましたが、以上です。

冒頭でも書いたのですが、基本的に Advent Calendarを書く年末だけにしか触らないので、来年はもう少し触れたらと思っています。

一個Bundleのネタもあるので、作れたらなと。

ラストは @cube_3110さんの記事です!

よろしくおねがいします!