php 实现orm
PHP 实现 ORM 的方法
ORM(Object-Relational Mapping)是将数据库表映射为对象的技术,简化数据库操作。以下是几种 PHP 实现 ORM 的方式:
使用现有 ORM 框架
-
Eloquent(Laravel 内置 ORM)
Eloquent 是 Laravel 默认的 ORM,提供简洁的语法操作数据库。// 定义模型 namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $table = 'users'; } // 查询数据 $users = User::where('active', 1)->get(); -
Doctrine
Doctrine 是一个功能强大的 ORM,支持 DQL(Doctrine Query Language)和复杂的关联关系。// 定义实体 namespace App\Entity; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity] #[ORM\Table(name: 'users')] class User { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: 'integer')] private $id; } // 查询数据 $users = $entityManager->getRepository(User::class)->findBy(['active' => 1]); -
Propel
Propel 是另一个流行的 ORM,支持代码生成和 ActiveRecord 模式。// 查询数据 $users = UserQuery::create()->filterByActive(1)->find();
自定义简易 ORM
-
基础 ActiveRecord 实现
通过继承基类实现简单的 ORM 功能。class Model { protected static $table; protected $attributes = []; public static function find($id) { $table = static::$table; $query = "SELECT * FROM {$table} WHERE id = ?"; $result = DB::query($query, [$id]); return new static($result); } } class User extends Model { protected static $table = 'users'; } $user = User::find(1); -
使用 PDO 封装
结合 PDO 实现简单的数据映射。class ORM { private $pdo; private $table; public function __construct($table) { $this->pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'); $this->table = $table; } public function where($conditions) { $where = implode(' AND ', array_map(fn($k) => "$k = ?", array_keys($conditions))); $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE {$where}"); $stmt->execute(array_values($conditions)); return $stmt->fetchAll(PDO::FETCH_ASSOC); } } $userORM = new ORM('users'); $users = $userORM->where(['active' => 1]);
性能优化建议
-
延迟加载
关联数据仅在需要时加载,减少不必要的查询。 -
缓存查询结果
对频繁访问的数据使用缓存(如 Redis)。 -
批量操作
使用批量插入或更新减少数据库交互次数。
User::insert([['name' => 'A'], ['name' => 'B']]);
以上方法可根据项目需求选择,现有框架适合快速开发,自定义 ORM 更适合特定场景优化。






