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

Model setters & getters best practice

What is the best pratice of using setters & getters in Model? My application has over 70 models and i used to generate setter & getters for all the models so i end up with many of these accessors never been used, i am in the way now to remove all these setters & getters and just access the field directly. @phalconphp @phalcon



98.9k
Accepted
answer
edited Nov '14

Use getters/setters is the best practice, you can implement custom logic there without having to check every use of the class:

Before:

public function setPrice($price)
{
     $this->price = $price;
}

Then a customer asks you to implement a validation to avoid prices slower than 100 being stored in the databse, this is easy if you have a setter:

public function setPrice($price)
{
    if ($price < 100) {
        throw new \LogicException('Price cannot be slower than 100');
    } 
    $this->price = $price;
}

But if you have used public properties this validation would be hard to implement.

edited Jun '15

Wouldn't be great if Phalcon overrides the setter and getter using magic methods so ANY property, no matter the visibility, uses the defined set or get only if exists. Same behaviour than it uses now when saving, etc...

So, in short, the model uses explicit set or get if they are defined, if not it just fallback to set the property or getting it as if where public. I like this way since I don't need to care for the entity/model logic I just set or get the properties and the model takes care of the stuff.

For example, actually I'm have a Collection object from the ODM. When I set a date to a property I use a settert to convert it to MongoDate, and a getter to return a DateTime. The setter is used on assignement but the getter is not. It's the same when converting ->toArray(); the property is retrieved without using the getter and I end up with a MongoDate. I don't want to manage it outside of the model and I would like to call the properties by its name, not using the set or get always.