jameslevi / objectify
是一个简单的PHP数据到对象包装库。
v1.0.3
2021-05-03 05:07 UTC
Requires
- php: >=5.3.0
README
是一个简单的PHP数据到对象包装库。
安装
- 您可以通过composer进行安装。
composer require jameslevi/objectify
- 如果不使用任何框架,请将composer的自动加载机制包含在代码的上部。
<?php if(file_exists(__DIR__.'/vendor/autoload.php')) { require __DIR__.'/vendor/autoload.php'; }
- 导入objectify类。
<?php use Graphite\Component\Objectify\Objectify;
入门指南
- 实例化一个新的objectify类。
$data = new Objectify(array( 'x' => 0, 'y' => 0, 'z' => 1, ));
- 您可以使用get方法访问每个数据。
echo $data->get("x"); // Will echo the value of x.
您也可以将数据作为对象属性检索。
echo $data->x; // Will echo the value of x.
- 您也可以更新每个数据的值。
$data->set("x", 100); // Set the new value of x.
您也可以将值设置为对象属性。
$data->x = 200; // Set the new value of x.
- 您可以使用add方法添加新数据。
$data->add("pi", 3.14);
- 您也可以检查数据对象是否包含关键字。
$data->has("x") // Returns true.
- 您可以从数据对象中删除数据。
$data->remove("z"); // This will remove z from the data object.
- 您可以返回所有数据对象键。
$data->keys(); // This will return all data object keys.
- 要检索对象数据,只需使用toArray方法。
$data->toArray(); // This will return all the data from the data object in array.
- 您也可以返回JSON格式的数据。
$data->toJson(); // This will return json formatted string.
扩展Objectify
- 您可以将objectify扩展为实体。例如,让我们以汽车作为实体。
<?php use Graphite\Component\Objectify\Objectify; class Car extends Objectify { public function setDriver($name) { $this->driver = "Mr. " . ucwords($name); } }
- 现在,让我们实例化一个新的汽车对象。
$car = new Car(array( 'manufacturer' => 'Honda', 'model' => 'Civic', 'type' => 'Sedan', 'driver' => null, ));
- 现在我们可以操作汽车对象数据。
$car->setDriver("james crisostomo");
- 现在,让我们输出我们的汽车驾驶员。
echo $car->driver; // Result will be "Mr. James Crisostomo".
静音数据对象
当数据对象被静音时,添加、更新或删除数据被禁用。
$data = new Objectify(["x" => 0], true); $data->set("y", 1); // Updating value is disabled. $data->add("y", 1); // Adding new data is disabled. $data->remove("x"); // Removing data is disabled.
克隆数据对象
您可以使用clone方法创建数据对象的多个副本。
$new_data = $data->clone(); // This will create an exact copy of the data object.
贡献
对于问题、关注点和建议,您可以通过nerdlabenterprise@gmail.com给James Crisostomo发邮件。
许可协议
本软件包是开源软件,遵循MIT许可证。