Skip to content

ElementItem

Andrey Kharanenka edited this page Jun 21, 2018 · 9 revisions

The class provides a flexible tool for single element data caching. The model data is cached as a data array. While working with an object of the ElementItem class the cached data array could be accessed through the object's properties ($obItem->id, $obItem->name).

Method List:

make($iElementID, $obElement = null)

  • iElementID - model element ID
  • obElement - model object, optional parameter

Static method used to create a new object of the ElementItem class. The element's data array is obtained from cache.

    $obItem = ElementItem::make(1);
    echo $obItem->id;

makeNoCache($iElementID, $obElement = null)

  • iElementID - model element ID
  • obElement - model object, optional parameter

Static method used to create a new object of the ElementItem class. Element's data array is created from the model's object without using cache.

    $obItem = ElementItem::makeNoCache(1);
    echo $obItem->id;

clearCache($iElementID)

  • iElementID - model element ID

Static method for clearing an element's cache.

    ElementItem::clearCache(1);

isEmpty()

Method returns true, if you failed to obtain the element's data from an object or cache.

    $obItem = ElementItem::make(10);
    if($obItem->isEmpty()) {
        return false;
    }

isNotEmpty()

Method returns true, if you successfully obtained the element's data from an object or cache.

    $obItem = ElementItem::make(10);
    if($obItem->isNotEmpty()) {
        //...
    }

toArray()

Method returns an array of the elements data.

    $obItem = ElementItem::make(10);
    return $obItem->toArray();

toJSON()

Method returns a JSON string of the elements data array.

    $obItem = ElementItem::make(10);
    return $obItem->toJSON();

getObject()

Method returns the model's object.

    $obItem = ElementItem::make(10);
    $obModel = $obItem->getObject();

Extending

You can add methods and properties in item class with extending constructors.

You can add custom fields to $cached array of model class.

Example

ElementModel::extend(function($obModel) {
    $obModel->addCachedField(['field_1', 'field_2']);
});

You can add fields to cached data array. You need add dynamic method in item class and add method name in $arExtendResult item property.

Example

ElementItem::extend(function($obItem) {
     
     $obItem->arExtendResult[] = 'addMyProperty';
             
     $obItem->addDynamicMethod('addMyProperty', function() use ($obItem) {

         $obModel = $obItem->getObject();
         $obItem->setAttribute('my_property', $obModel->my_property);
     });
});

Integration with Translate plugin

You can work with translatable fields without addition methods. The field will then contain the active language value.

echo $obElementItem->name;

You can use the getLangAttribute method to get field values for a non-active language.

echo $obElementItem->getLangAttribute( 'name', 'ru');