Download the PHP package nikserg/yii2-xml-model-behavior without Composer
On this page you can find all versions of the php package nikserg/yii2-xml-model-behavior. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download nikserg/yii2-xml-model-behavior
More information about nikserg/yii2-xml-model-behavior
Files in nikserg/yii2-xml-model-behavior
Package yii2-xml-model-behavior
Short Description Behavior to serialize model as XML
License
Informations about the package yii2-xml-model-behavior
yii2-xml-model-behavior
Behavior and trait to serialize model as XML
Install
composer require nikserg/yii2-xml-model-behavior
Usage
Core functionality is $model->asXml()
, which returns XML string, representating
object. To successfully use this, the $model
's class should satisfy conditions:
- Extends
yii\base\Model
- Uses behavior
nikserg\yii2\XmlModelBehavior\XmlModelBehavior
- Uses trait
nikserg\yii2\XmlModelBehavior\XmlArrayableTrait
- Overrides
fields()
function to use underscore functionality (see in Explaining Example section).
Simple example better than long explaination
Result of calling $file->asXml()
:
Explaining example
As you can see, behavior adds only in root model. Trait should be added to root
AND child models.
Parameter rootElement
can set the name of root XML element.
In fields()
function, those attributes, which names starts with underscore _
,
would be transformed into XML attributes of element. Other attributes would be
children elements.
Behind the scene
nikserg\yii2\XmlModelBehavior\XmlModelBehavior
provides $model->asXml()
function. In fact, it's just a wrapper around
Spatie\ArrayToXml\ArrayToXml\ArrayToXml::convert
function, which is not very
interesting. Interesting part starts with nesting models. To support unserscore
functionality, you must override toArray()
function, which is impossible in
behavior. This is where trait comes in game.