orm php 实现
ORM(对象关系映射)在 PHP 中的实现
PHP 中实现 ORM 主要通过第三方库或框架完成,以下是常见的实现方式及工具:
使用 Doctrine ORM
Doctrine 是 PHP 中最流行的 ORM 库之一,支持数据库抽象层(DBAL)和完整的 ORM 功能。
安装 Doctrine ORM:
composer require doctrine/orm
配置实体类(以 Product 为例):
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'products')]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private $id;
#[ORM\Column(type: 'string')]
private $name;
// Getter 和 Setter 方法
}
数据库操作示例:
$entityManager = EntityManager::create($conn, $config);
// 插入数据
$product = new Product();
$product->setName('Example');
$entityManager->persist($product);
$entityManager->flush();
// 查询数据
$repository = $entityManager->getRepository(Product::class);
$products = $repository->findAll();
使用 Eloquent ORM(Laravel 框架)
Eloquent 是 Laravel 内置的 ORM,语法简洁且功能强大。

定义模型:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['name'];
}
基本操作:
// 创建记录
$product = Product::create(['name' => 'Example']);
// 查询记录
$products = Product::where('name', 'Example')->get();
// 更新记录
$product->update(['name' => 'New Name']);
使用 Propel ORM
Propel 是另一个高性能的 PHP ORM 工具,支持代码生成。

安装 Propel:
composer require propel/propel
生成模型:
vendor/bin/propel model:build
使用示例:
$product = new Product();
$product->setName('Example');
$product->save();
$products = ProductQuery::create()
->filterByName('Example')
->find();
自定义简单 ORM 实现
如需轻量级实现,可通过 PDO 封装基础 ORM 功能:
class SimpleORM
{
protected $pdo;
protected $table;
public function __construct(\PDO $pdo, string $table)
{
$this->pdo = $pdo;
$this->table = $table;
}
public function find(int $id): ?array
{
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
}
}
选择建议
- 复杂项目:优先选择 Doctrine 或 Eloquent(Laravel 生态)
- 快速开发:Eloquent 集成度最高
- 性能敏感场景:Propel 或自定义轻量级实现
- 学习成本:Eloquent 最简单,Doctrine 功能最全
所有方案均需结合 Composer 进行依赖管理,并通过数据库迁移工具(如 Doctrine Migrations 或 Laravel Migrations)维护表结构。






