jameslevi / objectify
Is a simple data to object wrapper library in PHP.
v1.0.3
2021-05-03 05:07 UTC
Requires
- php: >=5.3.0
README
Is a simple data to object wrapper library in PHP.
Installation
- You can install via composer.
composer require jameslevi/objectify
- If not using any framework, include the composer autoload mechanism at the upper section of your code.
<?php if(file_exists(__DIR__.'/vendor/autoload.php')) { require __DIR__.'/vendor/autoload.php'; }
- Import the objectify class.
<?php use Graphite\Component\Objectify\Objectify;
Getting Started
- Instantiate a new objectify class.
$data = new Objectify(array( 'x' => 0, 'y' => 0, 'z' => 1, ));
- You can access each data using get method.
echo $data->get("x"); // Will echo the value of x.
You can also retrieve data as an object property.
echo $data->x; // Will echo the value of x.
- You can also update values of each data.
$data->set("x", 100); // Set the new value of x.
You can also set value as an object property.
$data->x = 200; // Set the new value of x.
- You can add new data using add method.
$data->add("pi", 3.14);
- You can also check if data object contains keyword.
$data->has("x") // Returns true.
- You can remove data from the data object.
$data->remove("z"); // This will remove z from the data object.
- You can return all data object keys.
$data->keys(); // This will return all data object keys.
- To retrieve the object data, just use the toArray method.
$data->toArray(); // This will return all the data from the data object in array.
- You can also return JSON formatted data.
$data->toJson(); // This will return json formatted string.
Extend Objectify
- You can extend objectify to an entity. For this example let's use car as an entity.
<?php use Graphite\Component\Objectify\Objectify; class Car extends Objectify { public function setDriver($name) { $this->driver = "Mr. " . ucwords($name); } }
- Now let's instantiate a new car object.
$car = new Car(array( 'manufacturer' => 'Honda', 'model' => 'Civic', 'type' => 'Sedan', 'driver' => null, ));
- We can now manipulate car object data.
$car->setDriver("james crisostomo");
- Now let's echo the driver of our car.
echo $car->driver; // Result will be "Mr. James Crisostomo".
Muted Data Object
Adding, updating or deleting of data is disabled when data object is muted.
$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.
Cloning Data Object
You can create multiple copies of data object using clone method.
$new_data = $data->clone(); // This will create an exact copy of the data object.
Contribution
For issues, concerns and suggestions, you can email James Crisostomo via nerdlabenterprise@gmail.com.
License
This package is an open-sourced software licensed under MIT License.