使用Doctrine的Zend-Framework项目。数据以对象的形式出现。在我的Zend视图中,我访问它的方式如下
$this->personData->getPersonAdress()->getPersonStreet();由于Person可能没有关联的地址,因此在回显之前,我们必须检查personadress是否存在以及personStreet是否已填满,否则可能会出现回显NULL错误。
因此,我们在isset中使用一些IFs:
<? if($this->personData->getPersonaddress()) echo $this->personData->getPersonaddress()->getPersonstreet(); else echo "''"?>示例(最坏情况):
<?
if(isset($this->address[0]) && is_object($this->address[0]))
{
$help2=$this->address[0]->getAddress();
if (isset($help2) && is_object($help2))
{
$help=$this->address[0]->getAddress()->getCountry();
if (isset($help) && is_object($help) && $help->getCountryId())
{
echo $this->address[0]->getAddress()->getCountry()->getCountryId();
}
}
}
?>我们需要一个解决方案,或者最终是一个Zend_view帮助器来简化响应这些值的过程。
任何想法都将受到高度赞赏..
发布于 2012-09-25 23:11:44
我自己解决了这个问题,实现了一个Zend View Helper,它打印出每个值,忽略非对象属性或NULL关联可能发生的错误。这对使用Zend Framework + Doctrine 2的每个人都很有用。
用法
而不是
$this->address->getAddress()->getCountry()->getCountryId()
Use (如果未设置,则提供值或默认值(0,第三个参数))
$this->Printsafe($this->address,"getAddress/getCountry/getCountryId",0)
代码跟随
class Printsafe extends Zend_View_Helper_Abstract {
public function isObjectOrSet($data, $properties)
{
if ($data != null)
{
if(is_object($data))
{
if (isset($properties[0]))
{
$actual_property = array_shift($properties);
return $this->isObjectOrSet($data->{$actual_property}(), $properties);
}
}
elseif(isset($data))
{
return $data;
}
else
return null;
}
else
return null;
}
/**
* Wants data and getters + properties
* Tests if they are set and returns requested value
* Returns empty value (instead of NULL) if any error occurs
*
* @param mixed $data - Example $this->personData
* @param string $properties - Example "getPersontype/getNotation"
* @param mixed $default - return value if not set. Default is empty string.
*
* @return mixed $value
*/
public function printsafe($data = null, $properties='', $default = '') {
$return = null;
if ($data != null)
{
if ($properties != '')
{
$prop_array = explode("/", $properties);
$return = $this->isObjectOrSet($data, $prop_array);
}
}
if ($return == null)
$return = $default;
return $return;
}
}发布于 2012-09-24 17:28:07
您可以使用HYDRATE_ARRAY告诉Doctrine返回一个数组,而不是映射的对象。
这样,就可以直接调用isset()。
发布于 2012-09-24 20:40:50
你可以用@作为链的前缀,这会抑制错误输出--这样你就不需要检查它了。如果它不存在,它将不会输出任何内容。
<?php echo @$this->personData->getPersonAdress()->getPersonStreet(); ?>通常不推荐使用@运算符,但在这种情况下,它似乎是一个合适的解决方案。(缺点是您可能会遗漏可能来自此行的其他错误)
https://stackoverflow.com/questions/12562156
复制相似问题