Active Record Conventions

I have a few questions about Active Records.

Just say I have a form and I want to collect a first and last name separately (Using the CForm form builder) and I want to save the data as a concatenated string in the DB as just name. In this case how do I represent these variables (firstName and lastName) on the CActiveRecord instance, do I create a pair of public member fields and store them there (declaring them as safe) or is there some other convention I should use. I know this way works but is it the right way?

Also if I want can I somehow manually create a CActiveRecordMetaData instance in say my CActiveRecord::init() and assign it the correct data so that Yii doesn’t have to build it. I know I can cache this metadata but does that persist across requests? If so, where is it being cached?

Thanks in advance.

You can create 2 public properties for firstName/lastName. Then create a method beforeSave like this:




public function beforeSave()

{

    // maybe only first or last name is set, or none at all:

    $names=array();

    if(!empty($this->firstName))

        $names[]=$this->firstName;

    if(!empty($this->lastName))

        $names[]=$this->lastName;

    if($names!==array())

        $this->fullName=implode(' ',$names;)

    return true;

}

Metadata is cached in whatever you configure as ‘cache’ application component. And yes, it’s persistent across requests - no need to fiddle around with that. Just set a ‘schemaCachingDuration’ in your ‘db’ component.

Thanks Mike.