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

Models Setters on direct assignment

I can't make it work, on phalcon 2.0.1.

a direct assigment should launch the setter, right?

class Users extends \Phalcon\Mvc\Model
{
    protected $password;
    public function getPassword() { return $this->password; }
    public function setPassword($password) { $this->password = 'prepend'.$password; }
}
$user->password = 'string';

echo $user->password; // 'string', not prepended as in setter.

It does not enter on the setter. Something I'm doing wrong? Or the setter only works for save, update, create, etc? The thing is, I'm pretty sure that this was working before..

If the property exists is not possible, and the password property is defined

Is it that true? It's setted as protected. Ok tried without defining it on the model. Neither seems to work

If the property exists is not possible, and the password property is defined



6.4k
Accepted
answer
edited May '15

Is it that true? It's setted as protected. Ok tried without defining it on the model. Neither seems to work

If the property exists is not possible, and the password property is defined

Sorry, I made a mess, do not know why :|. This only works with __get overloading https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L4032 and __set for relations

But implement this behavior is easy

    public function __set($property, $value) {
        $attributes = $this->getModelsMetadata()->getReverseColumnMap($this);

        if (NULL === $attributes) {
            $attributes = array_flip($this->getModelsMetadata()->getAttributes($this));
        }

        $method = "set{$property}";

        if (isset ($attributes[$property]) && method_exists($this, $method)) {
            return call_user_func([$this, $method], $value);
        }

        return parent::__set($property, $value);
    }

yep, it's easy but I wonder why it's not set on Phalcon by default? maybe it's incompatible with something in the ORM? Could it be implemented by default?

But implement this behavior is easy

It's perfectly compatible, see __set https://github.com/phalcon/cphalcon/blob/master/phalcon/mvc/model.zep#L3920, I do not think you want to name properties as alias names in relations