Hi all,
I have integrated Doctrine 2.3 with Yii but when i tried to map the form attributes with the Doctrine Model Object i had took a look to the function setAttributes in Yiilite.php
public function setAttributes($values,$safeOnly=true)
{
if(!is_array($values))
return;
$attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
foreach($values as $name=>$value)
{
if(isset($attributes[$name]))
$this->$name=$value;
else if($safeOnly)
$this->onUnsafeAttribute($name,$value);
}
}
Usually i write Doctrine models using protected fields and use setter and getter method to modify fields.
For this reason i have override the function setAttributes in this way.
For the same reason i have modified also the function attributesNames to get a list of fields that must be ONLY protected and have a "get" and "set" method associated.
namespace Annotations\mojo;
class CDoctrineFormModel extends \CFormModel {
private static $_names=array();
public function __construct($scenario='')
{
parent::__construct($scenario);
}
public function setAttributes($values, $safeOnly = true)
{
if (!is_array($values))
return;
$attributes = array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
foreach ($values as $name => $value)
{
if (isset($attributes[$name]))
{
$setter = 'set'.ucfirst($name);
$this->$setter($value);
}
else if ($safeOnly)
$this->onUnsafeAttribute($name, $value);
}
}
public function attributeNames()
{
$className = get_class($this);
if (!isset(self::$_names[$className]))
{
$class = new \ReflectionClass(get_class($this));
$names = array();
/* @var $property \ReflectionClass */
foreach ($class->getProperties() as $property)
{
$name = $property->getName();
if($property->isProtected() && $class->hasMethod('set'.$property->getName()) && $class->hasMethod('get'.$property->getName()) )
$names[] = $name;
}
return self::$_names[$className] = $names;
}
else
return self::$_names[$className];
}
}
I’m not a Yii pro developer, so i i have some questions:
-
Are there some reasons the model fields are public instead of protected or private?
-
Why yii access to the fields directly instead of unsing setter and getter?
-
Is it a reasonable thing modify into Yii the procedure used to access to the model fields? (doctrine or ActiveRecords or anything else ORM)
I have override these methods without modify the original method signature, but obviously if you use these methods, you have to modify your fields’s scope from public to protected, and insert setter and getter method for fields that you want to map
Thx all
Mojo