Symfony SQLite 教程
最后修改时间:2025年3月3日
Symfony SQLite 教程演示了如何在 Symfony 7.2 中使用 SQLite。我们创建了用于 JSON 输出的路由,使用 fixtures 填充数据库,并在 HTML 中显示数据。
Symfony
Symfony 是一套可重用的 PHP 组件,也是一个用于 Web 项目的 PHP 框架。Symfony 于 2005 年发布为自由软件。Fabien Potencier 是 Symfony 的最初作者。Symfony 在很大程度上受到了 Spring 框架的启发。
SQLite
SQLite 是一个轻量级、无服务器、独立的 SQL 数据库引擎。它非常适合小型应用程序、原型和测试。
设置项目
我们首先创建一个新的 Symfony 项目并安装必要的依赖项。
$ composer create-project symfony/skeleton symfony-sqlite "^7.2" $ cd symfony-sqlite
我们创建一个新的 Symfony 7.2 项目并导航到项目目录。
$ composer require symfony/orm-pack $ composer require --dev symfony/maker-bundle
我们安装 ORM pack 以支持数据库,并安装 maker bundle 以生成代码。
$ composer require symfony/validator $ composer require symfony/serializer
我们安装 validator 和 serializer 组件以进行数据验证和 JSON 输出。
配置 SQLite
我们在 .env 文件中配置 SQLite。
DATABASE_URL="sqlite:///%kernel.project_dir%/var/data.db"
这会将 SQLite 配置为使用 var 目录中名为 data.db 的文件。
$ php bin/console doctrine:database:create
我们创建 SQLite 数据库。
创建实体
我们创建一个 Product 实体来存储产品数据。
$ php bin/console make:entity Product
我们创建 Product 实体,包含字段:name (字符串) 和 price (十进制)。
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private string $name;
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
private string $price;
// Getters and setters
public function getId(): ?int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function setName(string $name): void
{
$this->name = $name;
}
public function getPrice(): string
{
return $this->price;
}
public function setPrice(string $price): void
{
$this->price = $price;
}
}
Product 实体现在为 price 字段使用了 Decimal,以确保货币值的精度。
$ php bin/console make:migration $ php bin/console doctrine:migrations:migrate
我们生成并运行迁移以创建数据库表。
使用 Fixtures
我们使用 fixtures 来填充数据库的示例数据。
$ composer require --dev doctrine/doctrine-fixtures-bundle
我们安装 fixtures bundle。
<?php
declare(strict_types=1);
namespace App\DataFixtures;
use App\Entity\Product;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class ProductFixtures extends Fixture
{
public function load(ObjectManager $manager): void
{
$products = [
['name' => 'Product A', 'price' => '19.99'],
['name' => 'Product B', 'price' => '29.99'],
['name' => 'Product C', 'price' => '39.99'],
];
foreach ($products as $data) {
$product = new Product();
$product->setName($data['name']);
$product->setPrice($data['price']);
$manager->persist($product);
}
$manager->flush();
}
}
ProductFixtures 类使用示例产品填充数据库。请注意,price 值现在作为字符串传递。
$ php bin/console doctrine:fixtures:load
我们将 fixtures 加载到数据库中。
创建用于 JSON 输出的路由
我们创建用于以 JSON 格式输出产品数据的路由。
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ProductController extends AbstractController
{
#[Route('/products', name: 'product_list', methods: ['GET'])]
public function list(EntityManagerInterface $em): JsonResponse
{
$products = $em->getRepository(Product::class)->findAll();
$data = [];
foreach ($products as $product) {
$data[] = [
'id' => $product->getId(),
'name' => $product->getName(),
'price' => $product->getPrice(),
];
}
return $this->json($data);
}
#[Route('/products/{id}', name: 'product_show', methods: ['GET'])]
public function show(Product $product): JsonResponse
{
return $this->json([
'id' => $product->getId(),
'name' => $product->getName(),
'price' => $product->getPrice(),
]);
}
}
ProductController 提供了两个路由:一个用于列出所有产品,另一个用于按 ID 显示单个产品。price 现在作为字符串返回。
在 HTML 中显示数据
我们创建了一个路由来在 HTML 中显示产品数据。
{% extends 'base.html.twig' %}
{% block title %}Product List{% endblock %}
{% block body %}
<h1>Product List</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
Twig 模板在 HTML 表中显示产品列表。price 显示为字符串。
#[Route('/products/html', name: 'product_list_html', methods: ['GET'])]
public function listHtml(EntityManagerInterface $em): Response
{
$products = $em->getRepository(Product::class)->findAll();
return $this->render('product/list.html.twig', ['products' => $products]);
}
我们添加了一个路由来渲染 HTML 中的产品列表。
运行示例
$ php bin/console server:start
我们启动开发服务器。
$ curl localhost:8000/products
[{"id":1,"name":"Product A","price":"19.99"}, ...]
$ curl localhost:8000/products/1
{"id":1,"name":"Product A","price":"19.99"}
我们使用 curl 测试 JSON 路由。
$ curl localhost:8000/products/html
通过在浏览器中访问 URL 来查看 HTML 中的产品列表。
在此教程中,我们在 Symfony 7.2 中使用了 SQLite,创建了用于 JSON 输出的路由,使用 fixtures 填充了数据库,并在 HTML 中显示了数据。
列出 所有 Symfony 教程。