Skip to content

josecelano/php-object-literal

Repository files navigation

Object

Latest Version Build Status Code Coverage Quality Score Total Downloads

Email

PHP 5.5+ library to create object literals like JavaScript or Ruby.

Creating object literals in PHP is not as easy (or elegant) as in JavaScript or Ruby.

You can create object literals this way:

$object = new Object([
    "name" => "Fido",
    "barks" => true,
    "age" => 10
]);

or

$object = new Object([
    "name" => "Fido",
    "barks" => true,
    "age" => 10,
    'say' => function ($self) {
        if ($self->barks) {
            return "Woof";
        }
        return "";
    }
]);

or

$object = new Object('{
    "name" : "Fido",
    "barks" : true,
    "age" : 10
}');

instead of:

$object = new Object();
$object->name = 'Fido';
$object->barks = true;
$object->age = 10;

This class was inspired by these two blog posts:

In fact, there is am old PHP RFC (2011-06-04) which have not been completely implemented:

This class could be used while the RFC is not implemented.

Install

Via Composer

$ composer require josecelano/php-object-literal

Features

  • Build from array.
  • Build from json.
  • Build from json with dynamic keys and values.

Testing

I try to follow TDD, as such I use phpunit to test this library.

$ composer test

TODO

  • Add magic getters and setters.
  • Allow to replace variable values in Json like JavaScript: From:
$object = new Object("{
    \"name\" : \"" . $valueForName . "\",
    \"barks\" : true,
    \"age\" : 10
}");

To:

$object = new Object('{
    "name" : $valueForName,
    "barks" : true,
    "age" : 10
}', get_defined_vars());

Replacing $valueForName by its value.

  • Allow current invalid PHP json formats.
$invalidJson1 = "{ 'bar': 'baz' }";
$invalidJson2 = '{ bar: "baz" }';
$invalidJson3 = '{ bar: "baz", }';
  • Add callable in json format.
  • Allow property value shorthand like ES6:
$object = new Object('{
    $name,
    $barks,
    $age
}', get_defined_vars());

License

The MIT License (MIT). Please see License File for more information.

About

Factory class for creating PHP object literals

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages