0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【PHP】SymfonyとMySQL(MariaDB)を接続からマイグレーションまで解説

Last updated at Posted at 2024-11-03

記事作成の背景

MariaDBとの連携をするための備忘録

検証環境

ソフトウェア バージョン
PHP 8.0*
Symfony 5.0*

MariaDBをインストール

公式サイトから、installをお願いします。

Doctorineのインストールを行う

ソースコードからデータベースを操作するにはORM マッパーのDoctorineをインストールしておきます。

composer require doctrine

MySQL(MariaDB)との接続情報の設定

接続するにはプロジェクトは以下の.envファイルの設定を変更する必要があります。
デフォルトでは、PostgreSQLを指定していますが、今回はMySQL(MariaDB)を使いので、下記の部分を修正します。

.env(28行目付近)
DATABASE_URL="mysql://(ユーザー名):(パスワード)@127.0.0.1:3306/(データベース名)"

.envファイルの全体のコードは下記の通りになります。

(プロジェクト名) / .env
# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env                contains default values for the environment variables needed by the app
#  * .env.local          uncommitted file with local overrides
#  * .env.$APP_ENV       committed environment-specific defaults
#  * .env.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env files.
#
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE NOR IN ANY OTHER COMMITTED FILES.
# https://symfony.com/doc/current/configuration/secrets.html
#
# Run "composer dump-env prod" to compile .env files for production use (requires symfony/flex >=1.2).
# https://symfony.com/doc/current/best_practices.html#use-environment-variables-for-infrastructure-configuration

###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=a81f1ef4d75e9b9f1ee3d6dc269e6b7d
###< symfony/framework-bundle ###

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# IMPORTANT: You MUST configure your server version, either here or in config/packages/doctrine.yaml
#
# DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
# DATABASE_URL="mysql://app:!ChangeMe!@127.0.0.1:3306/app?serverVersion=8&charset=utf8mb4"
#DATABASE_URL="postgresql://app:!ChangeMe!@127.0.0.1:5432/app?serverVersion=16&charset=utf8"
DATABASE_URL="mysql://root:pass1234@127.0.0.1:3306/symfonydb"
###< doctrine/doctrine-bundle ###

###> symfony/messenger ###
# Choose one of the transports below
# MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
###< symfony/messenger ###

###> symfony/mailer ###
# MAILER_DSN=null://null
###< symfony/mailer ###

データベースの作成

Doctorineのインストールと.env接続情報の設定が完了しました。
下記のコマンドでテーブルを作成しましょう。

php bin/console doctrine:database:create

Entityクラスを作成する

テーブルが作成出来たら、テーブル情報を作っていきましょう。

今回はProductエンティティクラスを作っていきます。

php bin/console make:entity Product

エンティティクラスの中身をみると、デフォルトでは下記のようになっています。

src/Entity/Product.php
<?php

namespace App\Entity;

use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ProductRepository::class)]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

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

}


Productエンティティクラスに、1つプロパティを追加してみましょう!
今回は、ユーザー名を追加しました。

src/Entity/Product.php
<?php

namespace App\Entity;

use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: ProductRepository::class)]
class Product
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

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

    #[ORM\Name]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?string $name ="";

    public function getName():?string
    {
        return $this->name;
    }

}


マイグレーションファイルを作成する

エンティティクラスを修正したら、下記のコマンドでマイグレーションファイルを作成しましょう。

php bin/console doctrine:migrations:diff

テーブルにマイグレーションを実行する
いよいよ、テーブルにマイグレーションファイル情報を反映します。
下記のコマンドで、実行します。

php bin/console doctrine:migrations:migrate

テーブルがっ更新されていたら完成です。

サンクスサイト

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?