开发者

Zend Framework's Model Abstract and null values

开发者 https://www.devze.com 2023-01-30 05:23 出处:网络
I\'m using s开发者_开发问答ome model abstract classes from Zend. Default_Model_Abstract: contains __set and __get and a setter and getter for every value and works as a virtual object.

I'm using s开发者_开发问答ome model abstract classes from Zend.

  • Default_Model_Abstract: contains __set and __get and a setter and getter for every value and works as a virtual object.
  • Default_Model_AbstractMapper: contains methods like save(), find(), fetchall() and so on.

I've found this solution several months ago at the Zend Quick Start documentation. But over the last months, I had some problems with it dealing with null values.

I've got a Zend_Form_Element_Select element which got it's value from database. It's values are IDs from a foreign key. So only a valid foreign key id or null is accepted. But the Zend_Form_Element_Select element is optional, so it's possible that I get a blank string as a result (->addMultiOption(null, 'Choose your option')). But this will give me an error, because a blank string isn't a valid foreign key id neither a null, which would also be allowed.

My first attemp was to check in my controller which handles the form, if the select elements value is an emptry string and change it to null. This is ugly and the problem was, that my setter changed null to 0, because I validate it with (int) $value.

public function setId($value)
{
    $this->_id = (int) $value;
    return $this;
}

So another approach was that I check in my setter, if the value is null and then I don't validate it with (int). That would look something like that.

public function setId($value)
{
    if($value !== null)
        $this->_id = (int) $value;
    return $this;
}

This would work fr this case, but I doesn't make sense because sometimes I want so reset an existing value to null. So I can't ignore values with null in the setter. So another approach would be:

public function setId($value)
{
    if($value !== null)
        $this->_id = (int) $value;
    else
        $this->_id = null;
    return $this;
}

But now it's really going ugly. I'm curious to see how you people would solve this problem. Because I think there has to be simple solution without just removing (int) in the setter. Because as far as I saw, this seems to be a common way to use the setter.

Best regards, Nico


I cannot think of any other way to do this logic-wise. If you find this to be too verbose, you could make the if/else into a ternary operator expression. This would make it a one-liner.

$this->_id = ($value !== NULL) ? (int) $value : NULL;
return $this;

Another option would be to move your if/else into a custom Zend_Filter like NullOrInt. This could be reused anywhere you need this check, e.g. at the controller level to validate request input or in a Zend_Form or in your Setter, etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消