2017 © Pedro Peláez
 

library php-object-literal

Factory class for creating PHP object literals

image

josecelano/php-object-literal

Factory class for creating PHP object literals

  • Saturday, March 25, 2017
  • by josecelano
  • Repository
  • 1 Watchers
  • 0 Stars
  • 0 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 1 Versions
  • 0 % Grown

The README.md

Object

Latest Version Build Status Code Coverage Quality Score Total Downloads, (*1)

Email, (*2)

PHP 5.5+ library to create object literals like JavaScript or Ruby., (*3)

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

You can create object literals this way:, (*5)

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

or, (*6)

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

or, (*7)

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

instead of:, (*8)

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

This class was inspired by these two blog posts:, (*9)

  • https://www.sitepoint.com/php-vs-ruby-lets-all-just-get-along/
  • https://www.phpied.com/javascript-style-object-literals-in-php/

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

  • https://wiki.php.net/rfc/objectarrayliterals

This class could be used while the RFC is not implemented., (*11)

Install

Via Composer, (*12)

$ 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., (*13)

$ 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:, (*14)

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

Replacing $valueForName by its value. - Allow current invalid PHP json formats., (*15)

$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., (*16)

The Versions

25/03 2017

dev-master

9999999-dev https://github.com/josecelano/php-object-literal

Factory class for creating PHP object literals

  Sources   Download

MIT

The Requires

  • php >=5.5

 

The Development Requires

object literal