ofelix03 / transformer
一个简单的关联(即键:值对)数据转换器,可以将数组数据的键转换为其他指定的键。它还支持将数据键对应的值转换为指定的PHP数据类型
Requires
- php: >=5.6.15
This package is not auto-updated.
Last update: 2024-09-26 02:44:15 UTC
README
一个简单的关联(即键:值对)数据转换器,可以将数组数据的键转换为其他指定的键。它还支持将数据值转换为指定的类型(例如整数、布尔值、字符串、\DateTime 等)
访问https://ofelix03.github.io/transformer/
本包的目标
- 简化数据键转换的过程。
- 减少应用程序控制器和业务逻辑中数据规范化活动(如数据键转换)的杂乱。
- 通过使用不同数据键转换的类来遵守DRY原则。
支持本包声明的代码
让我们首先从一个尝试展示在没有此包时我们通常会做什么的代码片段开始。
// An http request payload from a POST request $data = array( 'title' => 'Hey, am a title', 'description' => 'Hey, am simple description', 'pub_date' => '2016-05-10 10:05:30', 'comments_count' => '10', ); // In some projects, where you have received an http request // payload like the above, which needs to be normalized to // match some specific database field names, the snippet below // is a representation of what we might do without this package // (but with this package could have been done much more fluently without // cluttering our application controller or codebase); if (isset($data['title'])) { $data['newTitle'] = $data['title'] unset($data['title']); } if (isset($data['description'])) { $data['text'] = $data['description']; unset($data['description']); } if (isset($data['pub_date'])) { $data['published_date'] = $data['pub_date']; unset($data['pub_date']); } if (isset($data['comments_count'])) { // Here, we do just type casting, from string to integer $data['comments_count'] = (int) $data['comments_count'] } // Now $data contains the transformed keys with their associated data
现在,让我们尝试使用 Transformer 包来简化上述代码片段,并在过程中保持我们的代码 DRY。
// Using the same payload($data) as in the above snippet. // Here, we're using composer, hence we'll pull in composer's `vendor/autoload.php` // file to do it magic (autoloading) require 'vendor/autoload.php'; // Also, to use this library, we'll need the `Transformer` class, so will pull it // in like so: use Ofelix03\Transformer\Transformer // We first create a class PostTransformer that tailors our transformation // to our business model. This approach is recommend if we intend to use our // transform the same data set (payload) in different locations in our code base // PostTransformer is suppose to implement just 2 public methods // 1. createRequestKeys // 2. createMorphKeys // Both methods returns an array of key definitions which represent the definitions // of 'requestKeys' and 'morphKeys' as we will see in the code snippet below. class PostTransformer extends Transformer { // The returned array contains the keys expected from the request // payload (.i.e $data) public function createRequestKeys() { return array( 'title', 'description', 'pub_date', 'comments_count', ); } // The returned array contains keys expected to replace the // specified keys in the createRequestKeys() in positional indexing order public function createMorphKeys() { return array( 'newTitle', 'text', 'published_date', // This will cast the type of the value to a an integer 'comments_count:int' ); } } // Time to instantiate our new PostTransformer class, with the http request // payload ($data) we want to transform it keys, and hopefully do some casting // on some values that requires type casting. $postTransformer = new PostTransformer($data); // Now we transform the keys, and perform any necessary casting by invoking // transform() on $postTransformer like so: $result = $postTransformer->transform(); var_dump($result); // This should be the output of var_dump() the $result array (5) { ["title"] => string(15) "Some Post title" ["description"] => string(36) "Some post description here and there" ["published_status"] => bool(true) ["published_date"] => string(19) "20-06-2016 12:30:30" ["comments_count"] => int(0) }
安装
-
使用composer
composer require Ofelix03\Transformer
注意:确保在您想使用转换器包的文件的顶部包含
require vendor\autoload.php
。例如:假设我在名为main.php
的文件中使用此包,我的main.php
文件将如下所示require "vendor/autoload.php"; use Ofelix03\Transformer\Transformer; // Your code to use the Transformer class goes here. // Example: $transformedData = (new Transformer())->transform($payload, $reqKeys, $morphKeys);
-
使用github克隆 您也可以克隆此包的github仓库
只需按照以下步骤操作。确保您已在机器上设置了git环境。您可以在Git的官方网站上查看如何操作
-
步骤1
打开您的终端并运行以下
git clone
命令git clone https:\\www.github.com\ofelix03\transformer.git
-
步骤2
将
src
目录中的php文件复制到您的应用程序目录结构中的任何位置,并按以下顺序要求它们require 'app/root/folder/transformer/src/TypeCaster.php'; require 'app/root/folder/transformer/src/KeysBag.php'; require 'app/root/folder/transformer/src/Transformer.php';
-
用法
// Assume $data is the request payload that requires some of its keys // to be morphed into other keys. // This can be an http request payload or data set query from a database // or any data source. $data = array( 'title' => 'Some Post Title', 'description' => 'Some post description here and there', 'pub_status' => '1', 'pub_date' => '20-06-2016 12:30:30', 'comments_count => '10' ); // Here, $reqKeys list the keys in $data which are going to // be transformed to some other keys defined by the $morphKeys $reqKeys = array( 'description', 'pub_status', 'pub_date', 'comments_count' ); // $morpKeys holds a sequential listing of keys which // are to replace the keys specified in the $reqKeys. // The key listings should be have the same index position has the key it // would replace in the $reqKeys $morphKeys = array( 'text', 'published_status:bool', 'published_date', 'comments_cout:int' ); // Time to transform some keys using the `\Ofelix03\Transformer\Transformer` class // **NB**: Make sure to autoload `\Ofelix03\Transformer\Transformer` class before using it, // else it would not work. $transformer = new \Ofelix03\Transformer\Transformer($data, $reqKeys, $morphKeys); $result = $transformer->transform(); var_dump($result); // $result should now hold your transformed keys with their corresponding values // This is the result of var_dump($result) array (5) { ["title"] => string(15) "Some Post title" ["description"] => string(36) "Some post description here and there" ["published_status"] => bool(true) ["published_date"] => string(19) "20-06-2016 12:30:30" ["comments_count"] => int(0) }
\Ofelix03\Transformer\Tranformer上的其他API
-
Tranformer::isStrict(): bool
此方法检查是否应该以严格模式进行转换。返回布尔值(TRUE|FALSE)。在严格模式下,库检查
$reqKeys
是否与$morphKeys
长度相等,如果不相等则抛出异常。 -
Transformer::setStrict($mode = false)
此方法允许您设置转换模式。如果没有传递任何参数,则默认模式为
FALSE
。 -
Transformer::isTransformed(): bool
检查数据(或有效负载)是否已转换,这有助于节省时间,避免转换已经转换的数据,而是使用
Transformer::getMorphedData()
获取转换后的数据。 -
Transformer::setRequestKeys(array $reqKeys = [])
此方法允许您在创建
Ofelix03\Transformer\Transformer
类的实例后定义 $request 键。注意:如果需要调用此方法,应在调用Transformer::transform()
之前调用它,否则会抛出运行时异常。 -
Transformer::setMorphKeys(array $morphKeys = [])
此方法允许您设置在转换期间要替换 $request 键的键
-
Transformer::setRequestPayload(array $data)
此用于设置需要转换的数据。这可以在构建转换器对象时覆盖请求数据集。注意:在调用
Transformer::transform()
之前调用此方法 -
Transformer::transform($reqPayload = [], $strictMode = false): array
这是执行魔法的方法——将键转换为其他指定的键。必要时还可以执行类型转换。
-
$reqPayload 此参数是可选的。它是应用转换、使用 $requestKeys 和 $morphKeys 定义的数据
-
$strictMode 第二个参数表示转换使用的模式。它是可选的。请记住,这也可以通过前面讨论的
Transformer::setStrict()
设置。
-
-
Transformer::getMorphedData(): array
在调用
Transformer::transform()
之后调用此方法以获取转换后的数据(键已转换为其他键的数据)。
类型转换
以下是目前支持的数据类型转换。
- 整数 (int)
- 字符串 (string)
- 数组 (array)
- 布尔 (bool)
- 日期时间
贡献
您可以通过发送拉取请求来帮助改进此文档。希望我能够合并它。如果您发现了错误(语法或逻辑错误),我将很高兴接收修复该错误的拉取请求。但最好首先提出一个问题,如果它尚未被解决,我将很乐意将它分配给您。