Foreach Through Ar Attributes

I’m looking at writing a beforeSave(), and afterFind() functions that will loop through all the attributes of a model. If the dbType is ‘Date’ or ‘DateTime’ changing the attribute value to db format in beforeSave() and converting to locale.short format in afterFind().

I just can’t figure out how set the attribute given $model->tableSchema->columns->name.

The functions need to work given unknown number of columns and unknown names of attributes.

What I’ve got right now:


    public function beforeSave() {

        foreach($this->tableSchema->columns as $col) {

            if ($col->dbType == "date") {


                // this is where I want to do the conversion


            }

        }

    return parent::beforeSave();

}




Can anybody help?




foreach ($this->tableSchema->columns as $col) 

{

	$columnName = $col->name;

	// Probably cleaner to use a switch statement here

	if ($col->dbType === 'date')

	{				

		$date = new DateTime($this->{$columnName});

		$this->{$columnName} = $date->format('Y-m-d');

	}

	elseif ($col->dbType === 'datetime')

	{

		$date = new DateTime($this->{$columnName});

		$this->{$columnName} = $date->format('Y-m-d H:i:s');

	}

}



Thanks. I will try this.