tomvlk / sweet-orm
PHP的简单ORM,使用您已有的结构,无需命令行!
2.0.0-rc.2
2020-05-07 16:05 UTC
Requires
- php: >=7.1.0
- doctrine/annotations: ^1.10.2
- doctrine/collections: ^1.6.4
Requires (Dev)
- codacy/coverage: 1.4.3
- php-coveralls/php-coveralls: ^2.2.0
- phpunit/php-code-coverage: ^6.0.7
- phpunit/phpunit: ^7.5.20
README
简单的PHP ORM,无需使用命令行生成器和迁移工具,可以直接在现有表结构上工作。
配置和连接
要开始使用SweetORM,您需要对其进行配置,整个后端运行在PDO之上,需要一个连接或配置。
注入PDO连接
只有当您已经有一个指向目标数据库的PDO连接时,才能注入它。
\SweetORM\ConnectionManager::injectConnection($pdo); // Where $pdo is an instance of PDO. Active connection!
为单独的连接配置
当您没有PDO连接时,您需要在触摸任何实体之前设置数据库的配置。
\SweetORM\Configuration::set('database_driver', 'pdo_mysql'); // No other drivers support right now \SweetORM\Configuration::set('database_host', 'localhost'); \SweetORM\Configuration::set('database_port', 3306); // Optional, default 3306 \SweetORM\Configuration::set('database_db', 'sweet_test'); \SweetORM\Configuration::set('database_user', 'root'); \SweetORM\Configuration::set('database_password', '');
定义实体
实体是由数据库表结构组成的PHP类声明。您需要扩展SweetORM中的抽象Entity,并使用SweetORM中可用的注释。
/** * @EntityClass * @Table(name="post") <== The table has an attribute called 'name', which contains the table name in your database. */ class Post extends \SweetORM\Entity // Make sure you extend the SweetORM\Entity! { /** * @Column(type="integer", primary=true, autoIncrement=true) */ public $id; /** * @Column(type="integer") */ public $authorid; /** * @Column(type="integer") */ public $categoryid; /** * @var Category * @OneToOne(targetEntity="SweetORM\Tests\Models\Category") * @Join(column="categoryid", targetColumn="id") */ public $category; // This will be a relation, the category holds a Category entity instance, lazy fetched from your 'categoryid' column! /** * @Column(type="string") */ public $title; /** * @Column(type="string") */ public $content; }
其他示例,定义Category实体
/** * @EntityClass * @Table(name="category") */ class Category extends \SweetORM\Entity { /** * @Column(type="integer", primary=true, autoIncrement=true) */ public $id; /** * @Column(type="string") */ public $name; /** * @Column(type="string") */ public $description; // One To Many relationship /** * @var Post[] * @OneToMany(targetEntity="SweetORM\Tests\Models\Post") * @Join(column="id", targetColumn="categoryid") */ public $posts; // Will be available, and fetched when you refer to it using lazy loading. }
从数据库读取
从数据库读取和搜索非常简单,您有两种读取选项。
按主键获取
获取带有您请求的主键值的单个实体。简单快捷。
$category = Category::get(1); echo get_class($category); // Output: Category echo $category->id; // Output: 1
通过查询(查询构建器)获取
ORM有一个内置的查询构建选项,您可以通过实体类上的静态方法find()轻松触发。
$categories = Category::find()->all(); // $categories is now an array with all the categories in your database, all returned as Entity instances.
有关查询构建器的更多信息,请参阅查询构建部分。
保存
保存到数据库很简单。要创建实体的新实例,只需创建一个新的实体对象,如下所示
创建新实体
$category = new Category();
然后设置所有属性
$category->name = "Samples"; $category->description = "Sample posts";
最后保存
$category->save(); // -> returns true or false, true on success, false on failure, will also throw exceptions.
更改实体
要更改现有或获取的实体,只需更改属性值并再次使用save()
。
$category = Category::get(1); $category->name = "Samples - Old"; $category->save(); // -> returns true or false.
删除实体
要从数据库中删除实体,请使用实体上的delete()
方法。
$category = Category::get(1); // Delete $category->delete();
查询构建器
要查找实体,您可以使用查询构建器。这将交互式地构建一个SQL查询,而无需知道数据库的确切语法。
选择实体
使用多个查询构建器操作选择实体
$category = Category::find()->where('name', 'News')->one();
这与以下查询相同
SELECT * FROM category WHERE name = 'News' LIMIT 1;
构建方法
构建查询的方法
$query = Category::find(); $query->select(); $query->select('id name'); // Only fetch id and name column (not property!). $query->from('table'); // Select from table (not needed when using entity!) $query->where('column', '=', 'value'); // Middle is optional, default '='. $query->where(array('column' => 'value', 'column2' => array('=' => 'vallue2'))); // Complex where. $query->limit(50); // Limit by 50 rows $query->offset(10); // Offset by 10. $query->all(); // Execute query, fetchAll. $query->one(); // Execute query, fetch first row. // Write,update,delete $query->insert('table'); // Insert into table. $query->into('table'); // optional! $query->values(array('column' => 'value')); // Set insert data. $query->apply(); // boolean $query->update('table'); $query->set(array('column' => 'value')); // Set new data. $query->where('id', 1); $query->apply(); $query->delete('table'); $query->where('id', 1); $query->apply();
当然,您可以在查询构建器上链式执行所有操作。
验证和填充
对null和非null、类型和约束(定义为注释)的验证可以使在REST环境中使用ORM变得更好。
定义约束
class Test extends Entity { /** * @var string * @Column(type="string", null=true) * @Constraint( * startsWith="www.", <== Constraint for starting string. * minLength=20 <== Minimum string length. * ) */ public $longUrl; }
您可以使用以下约束
- minLength: 最小字符长度。数字。
- maxLength: 最大字符长度。数字。
- minValue: 要测试的最小int/float/double值。数字。
- maxValue: 要测试的最大int/float/double值。数字。
- valid: 验证特殊情况。可以是 'email'、'url'。字符串。
- regex: 正则表达式,将通过preg_match()进行测试。字符串。
- enum: 必须在给定的数组中。字符串数组。
- startsWith: 测试字符串是否以指定字符串开头。字符串
- endsWith: 测试字符串是否以指定字符串结尾。字符串
测试约束和要求
// We are going to use the ArrayValidator (will be selected automatically) $data = array( 'longUrl' => 'www.verylongurlthatvalidatescorrectly.com' ); $result = Test::validator($data)->test(); $result->isSuccess(); // true $result->getErrors(); // empty array.
使用原始数据填充和创建实体
从验证器创建
// We are going to use the ArrayValidator (will be selected automatically) $data = array( 'longUrl' => 'www.verylongurlthatvalidatescorrectly.com' ); $entity = Test::validator($data)->create(); // Entity = instance of Test. $entity->save(); // true
使用验证器提供的数据更新
// We are going to use the ArrayValidator (will be selected automatically) $entity = Test::get(1); // Instance of already existing test entity. $data = array( 'longUrl' => 'www.verylongurlthatvalidatescorrectly2.com' ); Test::validator($data)->fill($entity); // Entity = instance of Test. $entity->save(); // true, is now updated!
请记住,默认情况下,主键(复数)不能被验证器数据覆盖!