0

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?

Daniel Li
  • 14,976
  • 6
  • 43
  • 60
Csongor Fagyal
  • 514
  • 2
  • 10

1 Answers1

1

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 and age, attributes to your entity after reading it.
  • A before save filter, which join those attributes in a data attributes before saving the entity, and unsets username, email and age (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.

Mehdi Lahmam B.
  • 2,240
  • 16
  • 22
  • I prefer callbacks to filters, but I guess this is sort of Lithium's way to solve things :) Thanks! – Csongor Fagyal Jul 30 '12 at 12:53
  • Filters are callbacks. And you can override save() and find() methods in a BaseModel class too ;) – Mehdi Lahmam B. Jul 30 '12 at 14:08
  • I think I will just wait for the virtual attributes branch to get merged :) Or maybe I just merge it myself... I already had to do that with some part of the data branch, as SQLite support is somewhat broken in master. – Csongor Fagyal Jul 30 '12 at 17:53