Php 如果值不为';不匹配if语句

Php 如果值不为';不匹配if语句,php,symfony,Php,Symfony,在我的Clutch.php实体中有以下代码 /** * Set incubationTemp * * @param integer $incubationTemp * @return Clutch */ public function setIncubationTemp($incubationTemp) { $this->incubationTemp = $incubationTemp; if($incubationTemp > 77.5 &&am

在我的
Clutch.php
实体中有以下代码

/**
 * Set incubationTemp
 *
 * @param integer $incubationTemp
 * @return Clutch
 */
public function setIncubationTemp($incubationTemp)
{
    $this->incubationTemp = $incubationTemp;

    if($incubationTemp > 77.5 && $incubationTemp < 82.5){
        $estimatedHatchStart = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+60days');
        $estimatedHatchEnd = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+70days');
    } 
    else if($incubationTemp > 82.5 && $incubationTemp < 88.5) {
        $estimatedHatchStart = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+45days');
        $estimatedHatchEnd = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+55days');
    }
    else if($incubationTemp > 88.5 && $incubationTemp < 92.5) {
        $estimatedHatchStart = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+35days');
        $estimatedHatchEnd = new \DateTime($this->getLaidDate()->format('Y-m-d') . '+45days');
    } else {
        // Throw an error here
    }

    $this->setEstimatedHatchStart($estimatedHatchStart);
    $this->setEstimatedHatchEnd($estimatedHatchEnd);

    return $this;
}

不可能有“最佳”方式,但例外情况是一种选择:

class InvalidIncubationTemperatureException extends \DomainException {}
然后

else {
    throw new InvalidIncubationTemperatureException(
        'Whatever message you want'
    )
}
当你说“显示”一个可能意味着很多事情的错误时,让我们假设你在一个控制器上下文中

try {
    $clutch = new Clutch();
    $clutch->setIncubationTemp(0);
}
catch (InvalidIncubationTemperatureException $e)
{
    $this->addFlash('clutch_errors', $e->getMessage())
}
然后在你的小树枝上

{% set errors = app.session.flashbag.get('clutch_errors') %}
{% if errors|length %}
  {% for message in errors %}
    {{ message}}
  {% endfor %}
{% endif %}
或者任何你想要的机制


不过,更好的处理方法可能是使用

谢谢你,彼得。
类InvalidIncubationTemperatureException extends\DomainException{}
应该进入我的实体吗?实际上,我想我会仔细阅读验证。再次感谢:)对于符合PSR-0/4标准的自动加载器(Symfony使用),您绝对应该坚持每个文件一个类的体系结构。
{% set errors = app.session.flashbag.get('clutch_errors') %}
{% if errors|length %}
  {% for message in errors %}
    {{ message}}
  {% endfor %}
{% endif %}