A small marshalling library used to encode/decode data from classes

Overview

libMarshal

A small marshalling library used to encode/decode data from classes

How to use?

Using the library with objects is extremely simple.

MarshalTrait

This trait is the logic behind the marshaling/unmarshaling of objects. Like any other trait, you can use it through use MarshalTrait. Furthermore, this trait gives you access to two methods:

  • A class method: marshal() - Marshals the data into an array
  • A static method: unmarshal(array $data, bool $strict) - Unmarshals the data back into an object

Field

This attribute is one of the largest parts of the library as it is what determines what MarshalTrait marshals/unmarshals. If a property is not annotated with this attribute, it will not be handled.

The Field attribute accepts one argument: name. If no name is specified, MarshalTrait will use the property name as the name to marshal/unmarshal with.

As examples:

x] #[Field(name: "Specific Name")] public string $specificName; // When encoded, it will output to ["Specific Name" => x] public string $hiddenName; // This field will not be included in either marshalling methods.">
#[Field]
public string $name; // When encoded, it will output to ["name" => x]
#[Field(name: "Specific Name")]
public string $specificName; // When encoded, it will output to ["Specific Name" => x]
public string $hiddenName; // This field will not be included in either marshalling methods.

Using Objects in properties

The only prerequisite behind marshalling/unmarshalling an embedded object is to have the class set up with the MarshalTrait and Fields. Here is an example on how you would use that:

class Range {
	use MarshalTrait;
	
	#[Field]
	public int $min = 0;
	#[Field]
	public int $max = 10;
	#[Field]
	public int $default = 0;
}

class Options {
	use MarshalTrait;
	
	#[Field]
	public string $username = "TestUserName";
	#[Field]
	public Range $range;
}

Example

Here is a full example:

marshal(); // ["first-name" => "John", "last-name" => "Doe", "age" => 30, "email" => "[email protected]"] $data["first-name"] = "Jane"; // Changing the first name $data["email"] = "[email protected]"; // Changing the email // Unmarshalling $user = User::unmarshal($data); // User(firstName: "Jane", lastName: "Doe", age: 30, email: "[email protected]")">
class User {
	use MarshalTrait;
	
	#[Field(name: "first-name")]
	public string $firstName;
	#[Field(name: "last-name")]
	public string $lastName;
	#[Field]
	public int $age;
	#[Field]
	public string $email;
}

// NOTE: This uses promoted properties to make it easier to construct.
// You can learn more about this below.

// Marshalling
$user = new User(firstName: "John", lastName: "Doe", age: 30, email: "[email protected]");
$data = $user->marshal(); // ["first-name" => "John", "last-name" => "Doe", "age" => 30, "email" => "[email protected]"]

$data["first-name"] = "Jane"; // Changing the first name
$data["email"] = "[email protected]"; // Changing the email

// Unmarshalling
$user = User::unmarshal($data); // User(firstName: "Jane", lastName: "Doe", age: 30, email: "[email protected]")

Limitations

As the library stands, the constructor is never called when creating an object. This is intentional as argument ordering may have unintended side effects. If you want to be able to pass in parameters to an object, you can take advantage of PHP's promoted properties like so:

class User {
	use MarshalTrait;

	public function __construct(
		#[Field(name: "first-name")]
		public string $firstName,
		#[Field(name: "last-name")]
		public string $lastName,
		#[Field]
		public int $age,
		#[Field]
		public string $email
	) {}
}

This will allow you to create the objects through a constructor as usual while also declaring the properties.

Roadmap

At the moment, there are a few improvements that can be/or are being worked on. Here is a list of some of those improvements:

  • Add a limit to recursive objects when marshalling/unmarshalling (50?)
  • Cache properties for performance benefits

Issues

Any issues/suggestion can be reported here.

You might also like...
Small Library to Serve Images in PHP in a Better Way (Resize, Compress) with Caching Support

A library for serving images and optimizing, changing their sizes, this library uses the caching feature, and in addition, it is very fast and small in size. In addition to these features, this library also optimizes images.

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

A small library for validating International Bankaccount Numbers (IBANs) based on the IBAN Registry provided by SWIFT

nUberSoft is a small in-the-works framework Library for PHP

nUberSoft is a small in-the-works framework Library for PHP. It is a mix of old and new due to it's long development timeframe. Documentation is not as robust as it should be. The majority of this framework will work for non-Linux-based systems, but it is not tested and some security (.htaccess) are not read by Win servers.

YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic.

YL MVC Structure (PHP MVC) is a pattern made in PHP used to implement user interfaces, data, and controlling logic. It is built based on the combination of ideas from the Yii framework and Laravel framework (yl).

DTO Generator - PHP library for generating DTO classes

DTO Generator PHP library for generating DTO classes. Installation Use the package manager composer to install micro/dto. composer require micro/dto U

Open-source library used in Gigadrive projects with common PHP utilities

PHP Commons This library provides PHP utilities used in Gigadrive projects, provided for the open-source community. Functions are registered globally

Behat Transliterator library inherited from Doctrine1 and used in Behat for snippet generation

Behat Transliterator Behat Transliterator provides transliteration utilities for PHP. Transliteration data are ported from the Perl Text-Unidecode mod

This library implements a fuzzer for PHP, which can be used to find bugs in libraries

PHP Fuzzer This library implements a fuzzer for PHP, which can be used to find bugs in libraries (particularly parsing libraries) by feeding them "ran

A tool that can be used to verify BC breaks between two versions of a PHP library.

Roave Backward Compatibility Check A tool that can be used to verify BC breaks between two versions of a PHP library. Pre-requisites/assumptions Your

Comments
  • Renamer attribute

    Renamer attribute

    Renamer, a class attribute that holds a callable(string): string . It will be applied on all fields with empty string for the name argument. Example:

    use function ucfirst;
    
    #[Renamer("ucfirst")] class DataStructure {
    }
    
    • [x] Renamer attribute
    • [x] Unit test
    • [x] Logic implementation
    • [ ] ~~Tutorial~~ (no permission to edit wiki)
    opened by ghost 9
  • Tags

    Tags

    Is your feature request related to a problem? Please describe. I have faced 3 issues with i.e. values that come from saved configs marshaled via libMarshal:

    • A new version of a config might rename, remove or change the type of a value
    • Config values that are optional are hard to implement without assigning null as default, causing a trail of null checks
    • Sometimes you'd want specific values to be saved in different configs or arrays/json, i.e. a Tool (in MagicWE2, item with interactions. Brush might be the best example) should have runtime options and config options, one being used as file on disk and one i.e. as an array that is being serialized for async tasks.

    Describe the solution you'd like A possible solution i propose is adding an optional tags <list<string>> parameter. Then when using marshal() you can pass a list of tags you want serialized.

    Describe alternatives you've considered So far, none

    Additional context I got stuck at implementing libMarshal into MagicWE2 due to this. Right now the code isn't public though.

    But an example is the usersessions: https://github.com/thebigsmileXD/MagicWE2/blob/experiment/libMarshal/src/xenialdan/MagicWE2/session/UserSession.php#L29-L42 Some of those values are optional, for example $brushes. The brushcollection holds brushes, https://github.com/thebigsmileXD/MagicWE2/blob/experiment%2FlibMarshal/src/xenialdan/MagicWE2/session/data/BrushCollection.php#L28. These already have some kind of versioning implemented, but.. honestly not in a great way, they can't really be upgraded yet.

    The current format Session->save() produces is also not compatible with unmarshal due to some object arrays like BrushCollection being boiled down to an array that is not nested https://github.com/thebigsmileXD/MagicWE2/blob/0ed0c1a67c99314bcfbeafc36d4e826e1398e0a0/src/xenialdan/MagicWE2/session/UserSession.php#L279

    opened by thebigsmileXD 1
Releases(1.4.3)
Owner
Matthew Jordan
cs major
Matthew Jordan
Melek Berita Backend is a service for crawling data from various websites and processing the data to be used for news data needs.

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Chacha Nurholis 2 Oct 9, 2022
This library can be used, among other things, to retrieve the classes, interfaces, traits, enums, functions and constants declared in a file

marijnvanwezel/reflection-file Library that allows reflection of files. This library can be used, among other things, to retrieve the classes, interfa

Marijn van Wezel 5 Apr 17, 2022
Uses internet-connectable temperature sensors to provide cooling/heating assist for small buildings, as well as weather data

ambient-hvac Uses internet-connectable temperature sensors to provide cooling/heating assist for houses and other small buildings, as well as weather

null 3 Nov 25, 2021
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 560 Nov 20, 2022
Small utility library that handles metadata minification and expansion.

composer/metadata-minifier Small utility library that handles metadata minification and expansion.

Composer 134 Dec 26, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package.

Net A small, modern, PSR-7 compatible PSR-17 and PSR-18 network library for PHP, inspired by Go's net package. Features: No hard dependencies; Favours

Minibase 16 Jun 7, 2022
A small library to help run PHP servers easily and quickly.

PHP Server A small library to help run PHP servers easily and quickly. Installation composer require ahmard/php-server Usage PHP Built-In Server An i

Ahmad Mustapha 9 Dec 31, 2022
Small library providing some functional programming tools for PHP, based on Rambda

Functional library for PHP. Features: set of useful functions helpful in functional programming all functions are automatically curried every array ca

Wojciech Nawalaniec 5 Jun 16, 2022
A small PHP library to generate YouTube-like ids from numbers.

A small PHP library to generate YouTube-like ids from numbers. Use it when you don't want to expose your database ids to the user.

Vincent Klaiber 4.9k Dec 30, 2022