PHP ORM框架与简单代码实现
封面图
•
2025-09-23
•
PHP
76
0
0
0
在 PHP 中,ORM(Object-Relational Mapping)是一种将数据库表映射为对象的技术,使得开发者可以通过面向对象的方式操作数据库。常见的 PHP ORM 框架有: - **Eloquent**(Laravel 框架自带) - **Doctrine**(功能强大,适合复杂项目) - **RedBeanPHP**(轻量级,简单易用) - **Propel**(老牌 ORM) --- ## 一、使用 Eloquent(Laravel 中的 ORM 示例) ### 安装 Laravel(如果尚未安装) ```bash composer create-project laravel/laravel myproject ``` 进入项目目录: ```bash cd myproject ``` ### 创建模型和迁移 ```bash php artisan make:model User -mf ``` 这会创建一个 `User` 模型,并生成对应的迁移文件。 ### 迁移文件示例(`database/migrations/2023_10_01_000000_create_users_table.php`) ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } public function down() { Schema::dropIfExists('users'); } } ``` ### 运行迁移 ```bash php artisan migrate ``` ### 使用 Eloquent 操作数据库 ```php // 创建用户 $user = new App\Models\User(); $user->name = 'John Doe'; $user->email = 'john@example.com'; $user->password = bcrypt('password'); $user->save(); // 查询用户 $user = App\Models\User::find(1); echo $user->name; // 查询所有用户 $users = App\Models\User::all(); // 更新用户 $user = App\Models\User::find(1); $user->name = 'Jane Doe'; $user->save(); // 删除用户 $user = App\Models\User::find(1); $user->delete(); ``` --- ## 二、使用 Doctrine ORM(独立使用) ### 安装 Doctrine ```bash composer require doctrine/orm ``` ### 配置 Doctrine ```php <?php require_once 'vendor/autoload.php'; use Doctrine\ORM\Tools\Setup; use Doctrine\ORM\EntityManager; // 设置配置 $paths = [__DIR__ . "/src/Entity"]; $isDevMode = true; $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode); // 数据库连接参数 $connectionParams = [ 'dbname' => 'mydb', 'user' => 'root', 'password' => '', 'host' => 'localhost', 'driver' => 'pdo_mysql', ]; // 创建 EntityManager $entityManager = EntityManager::create($connectionParams, $config); ``` ### 定义实体类(`src/Entity/User.php`) ```php <?php 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; /** * @ORM\Column(type="string") */ private $name; /** * @ORM\Column(type="string", unique=true) */ private $email; // Getters and Setters public function getId() { return $this->id; } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; } } ``` ### 使用 Doctrine 操作数据库 ```php // 创建用户 $user = new App\Entity\User(); $user->setName('Alice'); $user->setEmail('alice@example.com'); $entityManager->persist($user); $entityManager->flush(); // 查询用户 $user = $entityManager->getRepository(App\Entity\User::class)->find(1); echo $user->getName(); // 更新用户 $user->setName('Bob'); $entityManager->flush(); // 删除用户 $entityManager->remove($user); $entityManager->flush(); ``` --- ## 三、手动实现简单的 ORM(不依赖框架) 虽然不推荐用于生产环境,但可以理解 ORM 的原理。 ### 1. 定义数据库连接类 ```php <?php class DB { protected $pdo; public function __construct() { $this->pdo = new PDO("mysql:host=localhost;dbname=mydb", "root", ""); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } public function query($sql, $params = []) { $stmt = $this->pdo->prepare($sql); $stmt->execute($params); return $stmt; } } ``` ### 2. 定义模型类 ```php <?php class User { protected $id; protected $name; protected $email; public function __construct($id = null) { if ($id) { $db = new DB(); $stmt = $db->query("SELECT * FROM users WHERE id = ?", [$id]); $row = $stmt->fetch(); if ($row) { $this->id = $row['id']; $this->name = $row['name']; $this->email = $row['email']; } } } public function save() { $db = new DB(); if ($this->id) { $db->query("UPDATE users SET name = ?, email = ? WHERE id = ?", [$this->name, $this->email, $this->id]); } else { $db->query("INSERT INTO users (name, email) VALUES (?, ?)", [$this->name, $this->email]); $this->id = $db->lastInsertId(); } } // Getters public function getId() { return $this->id; } public function getName() { return $this->name; } public function getEmail() { return $this->email; } // Setters public function setName($name) { $this->name = $name; } public function setEmail($email) { $this->email = $email; } } ``` ### 3. 使用示例 ```php $user = new User(); $user->setName("John"); $user->setEmail("john@example.com"); $user->save(); echo "User ID: " . $user->getId(); ``` --- ## 四、总结 | 特性 | Eloquent | Doctrine | 手动实现 | |------|----------|-----------|-----------| | 简单易用 | ✅ | ⚠️ | ✅ | | 功能丰富 | ✅ | ✅ | ❌ | | 适合大型项目 | ✅ | ✅ | ❌ | | 学习曲线 | ⚠️ | ⚠️ | ✅ | --- 如果你是初学者,建议从 **Eloquent** 或 **RedBeanPHP** 开始;如果是中大型项目,推荐使用 **Doctrine**。 如需我帮你写一个完整的项目结构或具体功能实现,也可以告诉我!
上一篇:
php获取指定目录下的所有文件列表
下一篇:
php获取网页header信息的方法
标题录入,一次不能超过6条
返回顶部
留言
留言
评论