PHPackages                             cangelis/data-models - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cangelis/data-models

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

cangelis/data-models
====================

Data models is the beautiful way of working with structured data such as JSON and PHP arrays

2.0.0(6y ago)63272[1 PRs](https://github.com/cangelis/data-models/pulls)MITPHPPHP &gt;=7.0CI failing

Since Nov 14Pushed 3y ago4 watchersCompare

[ Source](https://github.com/cangelis/data-models)[ Packagist](https://packagist.org/packages/cangelis/data-models)[ RSS](/packages/cangelis-data-models/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (2)Versions (4)Used By (0)

Data models
===========

[](#data-models)

[![Build Status](https://camo.githubusercontent.com/4d3aaa546ae5a6d58d914ca261d211aa10fa70ee1caa45aeed9f2618afaf8896/68747470733a2f2f7472617669732d63692e6f72672f63616e67656c69732f646174612d6d6f64656c732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/cangelis/data-models)

Data models is the beautiful way of working with structured data such as JSON, XML and php arrays. They are basically wrapper classes to the JSON and XML strings or php arrays. Models simplify the manipulation and processing workflow of the JSON, XML or php arrays.

Pros
----

[](#pros)

- Straightforward to get started (this page will tell you all the features)
- Avoid undefined index by design
- Dynamic access to the model properties so no need of mapping the class properties with JSON or XML attributes
- IDE auto-completion using `@property` docblock and make the API usage documented by default
- Has many and has one relationships between models
- Ability to assign default values for the attributes so the undefined attributes can be handled reliably
- Ability to add logic into the data in the model
- Cast values to known types such as integer, string, float, boolean
- Cast values to Carbon object to work on date attributes easily
- Ability to implement custom cast types
- Manipulate and work on the object models instead of arrays and make them array or serialize to JSON back

Install
-------

[](#install)

```
composer require cangelis/data-models:^2.0

```

JSON Usage
----------

[](#json-usage)

Imagine you have a JSON data for a blog post looks like this

```
$data = '{
    "id": 1,
    "author": "Can Gelis",
    "created_at": "2019-05-11 22:00:00",
    "comments": [
        {
            "id": 1,
            "text": "Hello World!"
        },
        {
            "id": 2,
            "text": "What a wonderful world!"
        }
    ],
    "settings": {"comments_enable": 1}
}';

```

You can create the models looks like this

```
use CanGelis\DataModels\JsonModel;
use CanGelis\DataModels\Cast\BooleanCast;
use CanGelis\DataModels\Cast\DateTimeCast;

/**
 * Define docblock for ide auto-completion
 *
 * @property bool $comments_enable
 */
class Settings extends JsonModel {

    protected $casts = ['comments_enable' => BooleanCast::class];

    protected $defaults = ['comments_enable' => false];

}

/**
 * Define docblock for ide auto-completion
 *
 * @property integer $id
 * @property string $text
 */
class Comment extends JsonModel {}

/**
 * Define docblock for ide auto-completion
 *
 * @property integer $id
 * @property author $text
 * @property Carbon\Carbon $created_at
 * @property Settings $settings
 * @property CanGelis\DataModels\DataCollection $comments
 */
class Post extends JsonModel {

    protected $defaults = ['text' => 'No Text'];

    protected $casts = ['created_at' => DateTimeCast::class];

    protected $hasMany = ['comments' => Comment::class];

    protected $hasOne = ['settings' => Settings::class];

}
```

Use the models

```
$post = Post::fromString($data); // initialize from JSON String
$post = new Post(json_decode($data, true)); // or use arrays

$post->text // "No Text" in $defaults
$post->foo // returns null which doesn't have default value
$post->created_at // get Carbon object
$post->created_at->addDay(1) // Go to tomorrow
$post->created_at = Carbon::now() // update the creation time

$post->settings->comments_enable // returns true
$post->settings->comments_enable = false // manipulate the object
$post->settings->comments_enable // returns false
$post->settings->editable = false // introduce a new attribute

$post->comments->first() // returns the first comment
$post->comments[1] // get the second comment
foreach ($post->comments as $comment) {} // iterate on comments
$post->comments->add(new Comment(['id' => 3, 'text' => 'Not too bad'])) // add to the collection

$post->toArray() // see as array
$post->toJson() // serialize to json

/*
{"id":1,"author":"Can Gelis","created_at":"2019-11-14 16:09:32","comments":[{"id":1,"text":"Hello World!"},{"id":2,"text":"What a wonderful world!"},{"id":3,"text":"Not too bad"}],"settings":{"comments_enable":false,"editable":false}}
*/
```

XML Usage
---------

[](#xml-usage)

It is pretty straightforward and very similar to JSON models.

Imagine an XML data:

```
$data = '

        Beckham1975-05-02
        Zidane1972-06-23

       Istanbul
       Turkey

';
```

You can setup a relationship looks like this:

```
use CanGelis\DataModels\XmlModel;
use CanGelis\DataModels\Cast\DateCast;

class Player extends XmlModel {

    // root tag name
    protected $root = 'Player';

    protected $casts = ['BirthDate' => DateCast::class];

}

class Address extends Xmlmodel {

    protected $root = 'Address';

}

class Team extends XmlModel {

    protected $root = 'Team';

    protected $hasMany = [
        'Players' => Player::class
    ];

    protected $hasOne = [
        'TeamLocation' => Address::class
    ];

    // the attributes in this array will be
    // behave as XML attributes see the example
    protected $attributes = ['Color'];

}
```

Once you setup the relationships and your data, you start using the data.

```
$team = Team::fromString($data);

echo $team->TeamLocation->City; // returns Istanbul
$team->TeamLocation->City = 'Madrid'; // update the city

echo $team->Players->count(); // number of players
echo $team->Players[0]->Name; // gets first player's name

echo $team->Color; // gets the Color XML attribute
$team->Color = '#000000'; // update the XML Attribute

echo get_class($team->Players[0]->BirthDate); // returns Carbon\Carbon
$team->Players->add(Player::fromArray(['Name' => 'Ronaldinho'])); // add a new player

echo (string) $team; // make an xml string
```

The resulting XML will be;

```

		Turkey
		Madrid

		Beckham1975-05-02
		Zidane1972-06-23
		Ronaldinho

```

Available Casts
---------------

[](#available-casts)

Here are the available casts.

```
    CanGelis\DataModels\Cast\BooleanCast
    CanGelis\DataModels\Cast\FloatCast
    CanGelis\DataModels\Cast\IntegerCast
    CanGelis\DataModels\Cast\StringCast
    // these require nesbot/carbon package to work
    CanGelis\DataModels\Cast\DateCast
    CanGelis\DataModels\Cast\DateTimeCast
    CanGelis\DataModels\Cast\Iso8601Cast

```

Custom Casts
------------

[](#custom-casts)

If you prefer to implement more complex value casting logic, data models allow you to implement your custom ones.

Imagine you use Laravel Eloquent and want to cast an in a JSON attribute.

```
// data = {"id": 1, "user": 1}

class EloquentUserCast extends AbstractCast {

    /**
     * The value is casted when it is accessed
     * So this is a good place to convert the value in the
     * JSON into what we'd like to see
     *
     * @param mixed $value
     *
     * @return mixed
     */
    public function cast($value)
    {
        if (!$value instanceof User) {
            return User::find($value);
        }
        return $value;
    }

    /**
     * This method is called when the object is serialized back to
     * array or JSON
     * So this is good place to make the values
     * json compatible such as integer, string or bool
     *
     * @param mixed $value
     *
     * @return mixed
     */
    public function uncast($value)
    {
        if ($value instanceof User) {
            return $value->id;
        }
        return $value;
    }
}

class Post {

    protected $casts = ['user' => EloquentUserCast::class];

}

$post->user = User::find(2); // set the Eloquent model directly
$post->user = 2; // set only the id instead
$post->user // returns instance of User
$post->toArray()

['id' => 1, 'user' => 2]
```

Contribution
------------

[](#contribution)

Feel free to contribute!

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

3

Last Release

2360d ago

Major Versions

1.0.1 → 2.0.02019-11-28

### Community

Maintainers

![](https://www.gravatar.com/avatar/ce2455306642be716064bd852d02059bfcb179045c8cadd7d1808078e44604db?d=identicon)[cangelis](/maintainers/cangelis)

---

Top Contributors

[![cangelis](https://avatars.githubusercontent.com/u/1162691?v=4)](https://github.com/cangelis "cangelis (23 commits)")

---

Tags

jsonxmlarraydatamapperdto

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cangelis-data-models/health.svg)

```
[![Health](https://phpackages.com/badges/cangelis-data-models/health.svg)](https://phpackages.com/packages/cangelis-data-models)
```

###  Alternatives

[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[openlss/lib-array2xml

Array2XML conversion library credit to lalit.org

31052.5M47](/packages/openlss-lib-array2xml)[jbzoo/data

An extended version of the ArrayObject object for working with system settings or just for working with data arrays

891.6M23](/packages/jbzoo-data)[hi-folks/data-block

Data class for managing nested arrays and JSON data.

1472.2k](/packages/hi-folks-data-block)[selective/transformer

A strictly typed array transformer with dot-access, fluent interface and filters.

3817.8k1](/packages/selective-transformer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
