PHPackages                             flaviovs/yii2-data-transformation - 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. flaviovs/yii2-data-transformation

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

flaviovs/yii2-data-transformation
=================================

Data transformation behavior for Yii2 models

0.0.1(7y ago)016.3k↓36%MITPHPPHP &gt;=5.6.0

Since Jan 18Pushed 7y ago1 watchersCompare

[ Source](https://github.com/flaviovs/yii2-data-transformation)[ Packagist](https://packagist.org/packages/flaviovs/yii2-data-transformation)[ RSS](/packages/flaviovs-yii2-data-transformation/feed)WikiDiscussions master Synced 1mo ago

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

Data transformation behavior for Yii2 models
============================================

[](#data-transformation-behavior-for-yii2-models)

This extension provides a behavior that makes easy to add data-transformed attributes into Yii2 models. It does that by creating virtual attributes that automatically convert data back-and-forth upon set/get operations.

Common use cases:

- You store dates in the database using Unix timestamps and/or date strings, but want to manipulate them as [DateTime objects](http://php.net/manual/en/class.datetime.php)
- Automatically data serialization
- Calculated attributes

See the [Data Transformation section in the ActiveRecord documentation](https://www.yiiframework.com/doc/guide/2.0/en/db-active-record#data-transformation)for more information about what problems this extensions helps you to solve.

Installation
============

[](#installation)

```
composer require flaviovs/yii2-data-transformation

```

How to use
==========

[](#how-to-use)

This extension provides an **abstract** class that you can use to create data transformation attributes. In other words, **you need to define your own behavior class to do the transformations you want**(or look for one created by somebody else).

To create a data transformation class, extend from `\fv\yii\behaviors\DataTransformation` and add the following methods:

- `transform($value)` (required) - apply data transformation to original model value `$value` (e.g. a Unix timestamp) and return the transformed result (e.g. a `\DateTimeImmutable`).
- `transformBack($value)` (optional) - apply data transformation to a transformed value `$value` (e.g. a `\DateTimeImmutable`) and return the original model representation (e.g. a Unix timestamp). This method is optional -- the inherited implementation just cast `$value` to `string`.

NULL handling
-------------

[](#null-handling)

By default data transformation methods will never receive `null`values -- `fv\yii\behaviors\DataTransformation` will automatically intercept then, and automatically return `null`. You can change this behavior by setting `$autoConvertNull` to `false` in your class (in which case, of course, your conversion methods must be prepared to handle `null` values).

For example:

```
class MyBehavior extends \fv\yii\behaviors\DataTransformation
{
    public $autoConvertNull = false;

    // (...)
}
```

Model usage
-----------

[](#model-usage)

When adding data-transformation behaviors to models, you should specify the attributes to be transformed in an `attributes` key in the configuration array. Attributes must be specified as key/value pair, where *key* is the transformed (virtual) attribute, and *value* is the original attribute.

Examples
========

[](#examples)

Automatic date conversion
-------------------------

[](#automatic-date-conversion)

This behavior will allow `\DateTime` objects access to Unix timestamps-based attributes:

```
class DateTimeImmutableBehavior extends \fv\yii\behaviors\DataTransformation
{
	protected function transform($value)
	{
		return new \DateTimeImmutable('@' . $value);
	}

    protected function transformBack($value)
    {
        return $value->getTimestamp();
    }
}
```

Now on your model:

```
class MyModel extends \yii\base\Model
{
	/**
	 * Unix timestamp attributes.
	 *
	 * @var integer
	 */
	public $created;
	public $updated;

	function behaviors()
	{
		return [
			'datetime' => [
				'class' => \app\behaviors\DateTimeImmutableBehavior::class,
					'attributes' => [
					'createdDateTime' => 'created',
					'updatedDateTime' => 'updated',
				],
			],
		];
	}
}
```

In your code:

```
// Print our timestamp property.
print_r($mymodel->created);
/*
1547346253
*/

// Print our data transformation property.
echo $mymodel->createdDateTime;
/*
DateTimeImmutable Object
(
    [date] => 2019-01-13 02:24:13.000000
    [timezone_type] => 1
    [timezone] => +00:00
)
*/

// Set value using date transformation.
$mymodel->updatedDateTime = new DateTime('2018-12-01 00:00:00');

// Output transformed value.
echo $mymodel->updated;
/*
1543651200
*/
```

Support
=======

[](#support)

Visit

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity45

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

Unknown

Total

1

Last Release

2677d ago

### Community

Maintainers

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

---

Top Contributors

[![flaviovs](https://avatars.githubusercontent.com/u/1832699?v=4)](https://github.com/flaviovs "flaviovs (1 commits)")

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/flaviovs-yii2-data-transformation/health.svg)

```
[![Health](https://phpackages.com/badges/flaviovs-yii2-data-transformation/health.svg)](https://phpackages.com/packages/flaviovs-yii2-data-transformation)
```

###  Alternatives

[phpdocumentor/reflection

Reflection library to do Static Analysis for PHP Projects

12521.4M109](/packages/phpdocumentor-reflection)[spatie/array-functions

Some handy array helpers

24561.1k2](/packages/spatie-array-functions)[cekurte/environment

A library to get the values from environment variables and process to php data types

5884.0k7](/packages/cekurte-environment)[forxer/gravatar

A library providing easy gravatar integration.

35202.0k8](/packages/forxer-gravatar)[netgen/layouts-ui

Netgen Layouts user interface

17110.8k2](/packages/netgen-layouts-ui)[ebidtech/collection

A set of interfaces and traits to speed up the creation of collections

13119.8k6](/packages/ebidtech-collection)

PHPackages © 2026

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