Featured image of post SymfonyでEntity生成時にAttributeを使う

SymfonyでEntity生成時にAttributeを使う

Twitter ツイート Hatena Bookmark ブックマーク

Symfony5.3でEntityを make:entity 使って生成したらannotationで生成されてしまいました。 せっかくphp8使っているのに…😇

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

namespace App\Entity;

use App\Repository\HogeRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=HogeRepository::class)
 */
class Hoge
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id;

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

}

ほんとうは以下のように生成してほしい・・・

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace App\Entity;

use App\Repository\HogeRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: HogeRepository::class)]
class Hoge
{

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: Types::INTEGER)]
    private ?int $id;

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

どうやらAttributeで生成出来るらしい

[make:entity] add php8 attribute support #920

ただし使えるのはv1.34.0からなのでのsymfony/maker-bundleをcomposer updateしておいたほうが良さそうです(2021/10/6現在)

1
$ symfony composer update symfony/maker-bundle

あとはyamlの設定を修正します。 mappings -> App -> typeを annotation から attribute に変更します。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'

        # IMPORTANT: You MUST configure your server version,
        # either here or in the DATABASE_URL env var (see .env file)
        #server_version: '13'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: attribute
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

あとはsymfony console make:entity すればattirbuteでEntityが生成されます。

comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。