dorofey / zf3-data-mapper
简单的Zf3数据映射器
0.0.1
2017-10-20 19:41 UTC
Requires
This package is not auto-updated.
Last update: 2024-10-03 07:55:08 UTC
README
基于zend-db
的简单数据映射器实现
这不仅是正在进行的工作,而是正在进行的工作的开始。甚至不要考虑使用它。
示例
定义我们的Post模型
EntityInterface定义了id的getter和setter,没有更多。
class Post implements EntityInterface { public $id; public $user; public $title; public function setId($id) ... public function getId() ... }
定义我们的映射器
class PostMapper extends Repository\Mapper\StandardMapper { protected static $entityClass = Post::class; protected static $table = 'posts'; protected static $features = [ Repository\Mapper\Feature\Relations::class => [ 'user' => [Repository\Hydrator\HasOne::class, User::class] ] ]; }
在配置中添加内容
[ 'mappers' => [ 'maps' => [ Post::class => PostMapper::class ], 'aliases' => [ 'posts' => Post::class ] ] ]
在你的代码中
$repository = $serviceLocator->get(\Repository\Repository\RepositoryPluginManager::class); $mapper = $repository->get(Post::class); $singlePost = $mapper->id(10); $allPosts = $mapper->fetch(); $somePosts = $mapper->fetch(['title' => 'My post title']); $somePosts = $mapper->fetch(function(Select $select){ $select->where(['title' => 'My post title'])->order('cteated_at')->limit(2); });
特性
\Repository\Mapper\Feature\SoftDelete
启用“软删除”功能。暴露recover
方法
// In your mapper protected static $features = [ Repository\Mapper\Feature\SoftDelete::class => 'deleted_at' // default field is 'deleted_at' ]; .... $post = $mapper->id(10); $mapper->delete($post); $mapper->recover($post);
\Repository\Mapper\Feature\Timestamps
启用创建和更新字段
// In your mapper protected static $features = [ Repository\Mapper\Feature\Timestamps::class => ['created_at', 'updated_at'] ]; ....
\Repository\Mapper\Feature\Transaction
// In your mapper protected static $features = [ Repository\Mapper\Feature\Transaction::class, ]; .... $mapper->withTransaction(); $mapper->update($post1); $mapper->update($post2); $mapper->insert($post3); $mapper->delete($post4); $mapper->commitTransaction();
\Repository\Mapper\Feature\Relations
// In your mapper protected static $features = [ Repository\Mapper\Feature\Relations::class => [ 'users' => [HasManyThrough::class, User::class, ['post', 'user'], 'post_users'], 'author' => [HasOne::class, User::class], ], ]; .... $post = $mapper->withRelation(['users', 'author])->id(10); $post->author->name;
\Repository\Mapper\Feature\SelectStrategy (进行中)
允许你定义自定义查询逻辑或隐藏实现细节。
如果你打算将映射器暴露给ViewHelper或任何猴子可以访问的地方,这将很有用。
// In your mapper protected static $features = [ Repository\Mapper\Feature\SelectStrategy::class, ]; .... $post = $mapper->withStrategy(['limit' => 10, 'where' => 'author=2,age<55', 'order' => '-created_at'])->fetch(); // Or simply $post = $mapper->fetchWithStrategy(['limit' => 10, 'where' => 'author=2,age<55']);