stidges / laravel-db-normalizer
将所有数据库结果统一化到统一的接口,轻松交换仓库。
0.1.0
2014-03-12 20:38 UTC
Requires
- php: >=5.4.0
- illuminate/database: 4.1.*
Requires (Dev)
- mockery/mockery: dev-master
- phpunit/phpunit: 4.0.*
This package is auto-updated.
Last update: 2024-08-29 03:47:40 UTC
README
此Laravel包允许您通过提供一个数据库结果的统一接口,轻松交换您的仓库实现。
它拦截您的结果并将它们转换为集合和实体。这样,无论您使用Eloquent、查询构建器还是任何其他实现,结果都将相同!
入门
您可以通过Composer安装此包,只需将其添加到您的composer.json文件中
{ "require": { "stidges/laravel-db-normalizer": "0.*" } }
在将此包添加到您的composer.json文件后,请确保更新您的依赖项
composer install
接下来,您可以选择以下两种方法之一
1. 启用自动统一化
通过注册此包的ServiceProvider类,所有运行的查询都将自动统一化为统一的Collection
和Entity
类。将以下行添加到您的app/config/app.php
文件中
'Stidges\LaravelDbNormalizer\DbNormalizerServiceProvider',
当使用Eloquent模型时,它们应扩展NormalizableModel
类
use Stidges\LaravelDbNormalizer\NormalizableModel; class User extends NormalizableModel { // ... }
2. 禁用自动统一化
如果您希望有更多控制权,不要注册ServiceProvider。这样,您就可以控制何时将结果转换为类。为此,使用Normalizer类。请确保您始终向normalizer传递一个数组!
use Stidges\LaravelDbNormalizer\Normalizer; //... // Example using the query builder $result = DB::table('users')->get(); // ... Do stuff with the result. $normalized = with(new Normalizer)->normalize($result); // Example using Eloquent $user = User::find(1); // ... Do stuff with the user. $normalized = with(new Normalizer)->normalize($user->toArray()); // Example using Eloquent collection $users = User::all(); // ... Do stuff with the users. $normalized = with(new Normalizer)->normalize($users->toArray());
使用统一化的结果
此包提供2个类
- 一个
Collection
类。目前,此类只是扩展Laravel的Illuminate\Support\Collection
类。 - 一个
Entity
类。此类可以包含嵌套的实体和集合(关系)。它提供了一个流畅的接口来访问实体的属性,可以使用熟悉的toJson
和toArray
方法将其转换为数组或JSON。除此之外,它还提供了一个getDirtyAttributes()
函数,允许您获取创建后更改的所有属性。
示例用法
有关如何使用此包的示例,请查看examples
目录!
贡献
欢迎所有建议和pull请求!如果您进行了任何实质性更改,请请提供与您的pull请求一起的测试!
许可证
版权(c)2014 Stidges - 在MIT许可证下发布。