virtual attributes with validators, splitting/joining a column value to create them
Question
I have an existing SQL table the schema of which I cannot modify, and I would like to create a Lithium data model for it. The problem is that one column contains multiple "fields" separated by a special character.
E.g.
data = "username|email|age"
I would need to:
- split the value of the column after the row was read, and create "virtual" attributes
- be able to assign to these virtual attributes
- join the virtual attributes to create a valid column value before save
- create validators for the virtual attributes
- use html->form to create form fields for the virtual attributes
I tried to figure out how to do this, but there seems to be no easy way. Not even a hard way :) Any ideas?
Solution
Magic virtual attributes aren't supported in Lithium out of the box. There is an ongoing work and discussion about that here https://github.com/UnionOfRAD/lithium/pull/569.
That said, you can almost solve this problem with instance methods in your Model + filters on save and find.
- An after find filter, which sets
username
,email
andage
, attributes to your entity after reading it. - A before save filter, which join those attributes in a
data
attributes before saving the entity, and unsetsusername
,email
andage
(to avoid saving them).
Maybe you'll need Model instance methods too like
public function username($entity) {
/* split here $entity->data by "|" and keep only what do you want */
return $username;
}
Then you can call anywhere $user->username() to get the username only.
That should solve your problem until this feature will be shipped in Lithium.