About model property types, events and behaviors #16538
Replies: 2 comments
-
Ohhh! i will try to make it solve. Catlikesbest |
Beta Was this translation helpful? Give feedback.
-
Aren't the only things you can exchange with a database basically numbers or strings? |
Beta Was this translation helpful? Give feedback.
-
Hello,
I've started an app following documentation and what was recommended. I've started making a model User with the id, first_name, last_name , created_at and updated_at. Very simple.
The properties are all typed hinted, using int for id, string for names and DateTimeImmutable for the created_at and updated_at.
They also have getters and setters , each with their appropriate type declaration, eg:
I noticed that you can not make property types when you declare the properties. My initial purpose was to make them all nullable, eg:
Then I read that phalcon returns all fields in string format only and new Model objects are assign null by default, so I just used protected $property only. Lastly to get the conversion to the specific type, I used model events
and so far, these act as I expected if the correct approach is to use property without types, setters/getters with types.
I later saw about behaviours and I can say the idea is fabulous and very easy to reuse code, yet it seems I stumble on a particular race condition thing that I'm unsure it is by design or not. Using events, I can type hint the getters and setters just fine, but if I use behaviour class, I have to set my getters as string, only then will the behaviour take charge and update the model as I expected. So when using the behaviour, my model looks like that this
Otherwise you get the error:
So with all the ramblin out of the way, I believe there are two ways to achieve this, while in all cases, the property is set without type, or at least set to ?string maybe. The null value is not required.
$this->property
so it goes around the getter type.It seems to me that I'm overcomplicating things with getters and setters, what's the proper standard way to achieve types with model, using behaviors? It seems this is the more elegant way, yet it I'm not sure what I'm doing wrong. Why do getters need to be set as ?string while setters work fine. In my Behaviour class, I do access the property as in within normal events with $model->{$field}
Thank you, and look forward to someone explaining if there's something I did wrong.
Beta Was this translation helpful? Give feedback.
All reactions