We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Many Getters and Setters

Hi,

I have a doubt in the model. I'm with many fields in the table and so many get and sets in the model. I wonder how you are doing when you have many just like me.

I tried to do something to help, but to no avail

  public function set($field, $value) {
        $this->$field = $value;
  }

  public function get($field) {
        return $this->$field;
  }

Someone uses a solution to decrease code?



8.3k
edited Oct '14

I suggest to read the best answer here:

https://stackoverflow.com/questions/6184337/best-practice-php-magic-methods-set-and-get

Copy/pasting here the response:

this is slower (than getters/setters)

there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the @property phpdoc annotation but that requires to maintain them: quite a pain)
the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.

added after edit: having getters for properties is more consistent with "real" methods where getXXX() is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName() (returns private property) and $user->getToken($key) (computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.

Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.

Getters and setters are a pain to write (I hate them) but they are worth it.

Truth. It is a headache to write 10/15 times and gets sets. I will continue to write one by one. But it would be interesting to someone 'invent' a more developer friendly alternative hahahahah



8.3k

I am new with phalcon, but maybe there is models generator? I see there is dev-tools, maybe you can generate all your models files quickly?

Otherwise, check this site:

https://www.phpobjectgenerator.com/

I used this in past to generate my models files.

There are also other generator, try google.



33.8k

I have a workaround in my app I did time ago, but it isn't the same as I want, cause of not knowing how to get the caller function name in a ´´´protected´´´ super function (yeah, I can do a protected static one, but I don't want to pass the model object to the function as an arg).