Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, January 6, 2013

PHP: declarative property validation through document

Here is an attempt to define validation rules in document metadata and read it through reflection to validate the property against metadata. The metadata should be a valid json (verify using jsonlint.org).

Keeping it in metadata has the following benefits:

1. keeps it close to the property
2. easier to manage and read ( otherwise a complex structure if specified in another attribute )
3. is cool to do

Having type to php violates the dynamically typed nature of it. This is only in case you need it.

Saturday, January 5, 2013

PHP:json_encode private properties

json_encode( $obj ) works with public properties. In case you have private properties, you can implement jsonSerialize()::JsonSerializable. json_encode for objects of this class will create json with properties or value you specify in jsonSerialize. The output of jsonSerialize should either be array (normal or associative). The below code has a provision to filter attributes added in the $exclude_properties_to_json_arr var.Works with PHP 5.4 and above.