星云
发布于 2025-01-25 / 10 阅读
0
0

Symfony项目初始化需要安装的工具组件(三)

在 Symfony 项目中安装 Doctrine 非常简单。Doctrine 是 Symfony 的默认 ORM(对象关系映射)工具,用于与数据库交互。以下是安装 Doctrine 的详细步骤:

1. 安装 Doctrine

运行以下 Composer 命令来安装 Doctrine:

composer require symfony/orm-pack
  • symfony/orm-pack 是一个 Composer 包,包含了 Doctrine ORM 及其依赖项。

2. 配置数据库连接

安装完成后,Doctrine 会自动配置。你需要在 .env 文件中设置数据库连接信息。找到以下行并修改为你的数据库配置:

DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=8.0"
  • mysql: 数据库类型(如 mysqlpostgresqlsqlite)。

  • db_user: 数据库用户名。

  • db_password: 数据库密码。

  • 127.0.0.1:3306: 数据库主机和端口。

  • db_name: 数据库名称。

  • serverVersion: 数据库服务器版本。

例如,如果你使用的是 MySQL 数据库,配置可能如下:

DATABASE_URL="mysql://root:password@127.0.0.1:3306/my_database?serverVersion=8.0"

3. 创建数据库

运行以下命令来创建数据库:

php bin/console doctrine:database:create
  • 如果数据库已存在,此命令会跳过创建。

4. 创建实体

实体是映射到数据库表的 PHP 类。使用以下命令创建实体:

php bin/console make:entity

按照提示输入实体名称和字段信息。例如,创建一个 Product 实体:

Class name of the entity to create or update:
> Product

New property name (press <return> to stop adding fields):
> name

Field type (enter ? to see all types) [string]:
> string

Field length [255]:
> 255

Can this field be null in the database (nullable) (yes/no) [no]:
> no

New property name (press <return> to stop adding fields):
> price

Field type (enter ? to see all types) [string]:
> float

Can this field be null in the database (nullable) (yes/no) [no]:
> no

New property name (press <return> to stop adding fields):
> (按回车结束)

生成的实体类位于 src/Entity/Product.php

5. 生成数据库迁移

Doctrine 使用迁移工具来管理数据库模式的变化。运行以下命令生成迁移文件:

php bin/console make:migration

生成的迁移文件位于 migrations/ 目录。

6. 执行数据库迁移

运行以下命令将迁移应用到数据库:

php bin/console doctrine:migrations:migrate
  • 如果这是第一次运行迁移,Doctrine 会创建必要的表。

7. 验证安装

运行以下命令检查 Doctrine 是否安装成功:

php bin/console doctrine:schema:validate

如果输出显示数据库模式与实体映射一致,说明安装成功。

8. 操作数据库

以下是一些常用的 Doctrine 命令:

  • 插入数据

    use App\Entity\Product;
    use Doctrine\ORM\EntityManagerInterface;
    
    public function addProduct(EntityManagerInterface $entityManager): Response
    {
        $product = new Product();
        $product->setName('Laptop');
        $product->setPrice(999.99);
    
        $entityManager->persist($product);
        $entityManager->flush();
    
        return new Response('Saved new product with id ' . $product->getId());
    }
  • 查询数据

    use App\Repository\ProductRepository;
    
    public function showProduct(ProductRepository $productRepository): Response
    {
        $product = $productRepository->find(1); // 根据 ID 查询
    
        if (!$product) {
            throw $this->createNotFoundException('Product not found');
        }
    
        return new Response('Product: ' . $product->getName());
    }
  • 更新数据

    use App\Entity\Product;
    use App\Repository\ProductRepository;
    use Doctrine\ORM\EntityManagerInterface;
    
    public function updateProduct(ProductRepository $productRepository, EntityManagerInterface $entityManager): Response
    {
        $product = $productRepository->find(1);
    
        if (!$product) {
            throw $this->createNotFoundException('Product not found');
        }
    
        $product->setPrice(899.99);
        $entityManager->flush();
    
        return new Response('Updated product price');
    }
  • 删除数据

    use App\Entity\Product;
    use App\Repository\ProductRepository;
    use Doctrine\ORM\EntityManagerInterface;
    
    public function deleteProduct(ProductRepository $productRepository, EntityManagerInterface $entityManager): Response
    {
        $product = $productRepository->find(1);
    
        if (!$product) {
            throw $this->createNotFoundException('Product not found');
        }
    
        $entityManager->remove($product);
        $entityManager->flush();
    
        return new Response('Deleted product');
    }

9. 总结

  • 使用 symfony/orm-pack 安装 Doctrine。

  • .env 文件中配置数据库连接。

  • 使用 make:entity 创建实体。

  • 使用 make:migrationdoctrine:migrations:migrate 管理数据库模式。

  • 通过实体管理器和仓库操作数据库。


评论