我的Clutch.php
entity
内有以下代码。
/**
* 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;
}
如果传递的值介于我在if语句中可以看到的值之间,那么它可以正常工作。我想做的是强制显示错误,以显示$incubationTemp
的值是否超出正在检查的值。实现这一目标的最佳方法是什么?
编辑:
根据彼得的回答。这完美地运作了:
use Symfony\Component\Validator\Constraints as Assert;
// ...
/**
* @var integer
*
* @ORM\Column(name="incubation_temp", type="integer")
* @Assert\Range(
* min = 78,
* max = 92,
* minMessage = "The fahrenheit value you have entered is not a suggested value for incubating leopard geckos. Please make sure the value is at least {{ limit }}°f.",
* maxMessage = "The fahrenheit value you have entered is not a suggested value for incubating leopard geckos. Please make sure the value is lower than {{ limit }}°f."
* )
*/
private $incubationTemp;
答案 0 :(得分:1)
不可能有最好的&#34;方式,但例外是一种选择:
class InvalidIncubationTemperatureException extends \DomainException {}
然后
else {
throw new InvalidIncubationTemperatureException(
'Whatever message you want'
)
}
当你说&#34; show&#34;错误可能意味着许多事情,但让我们假设您处于控制器环境中
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 %}
或者你喜欢的任何机制。
然而,处理此问题的更好方法可能是使用validation