Cmodel - Adding Attributes Dynamically

Hi,

I am just curious - will it be possible to add new attributes into CModel (or whatever equivalent in Yii2) dynamically, during the run-time?

In some situations, we dont exactly know the structure of the CModel.

The only ways is to override CComponent::__set method, which is not nice.

Currently this is one of few missing features I guess:-)

Thank you.

Lubos

Yes, you will be able to do so but you’ll need to override default attributes method that’s returning public and non-static properties currently:




/**

 * Returns the list of attribute names.

 * By default, this method returns all public non-static properties of the class.

 * You may override this method to change the default behavior.

 * @return array list of attribute names.

 */

public function attributes()

{

	$class = new \ReflectionClass($this);

	$names = array();

	foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {

		$name = $property->getName();

		if (!$property->isStatic()) {

			$names[] = $name;

		}

	}

	return $names;

}



Ah, interesting to see fragment from Yii 2:-)

However, the method above is a getter. I was asking about a setter - setting some attribute that during rendering would be attached (injected) into CModel.

Thanx a lot.

Setter relies on what is returned from attributes so it’s possibe to achieve what you need. So you’ll end up with something like FlexibleModel extends Model {} that you’ll use as a base for such models.

OK, thank you - i will wait to see Yii2 CComponent magic methods (__set, __get).