我正在使用propel http://www.propelorm.org/documentation/09-inheritance.html中的以下功能。
我也在使用Symfony2和Twig
我有一个使用上述特性的类结构,如下所示
class Event {}
class Birthday extends Event {}
class Walking extends Event {}
现在,我将一个事件对象传递给一个twig模板,我想知道它是什么类型的事件
例如,如果是生日,我想要显示蛋糕的图像;如果是步行活动,我想要显示地图路线。
我不能在Twig中使用instanceof,因为这个特性不存在。现在有没有人知道为什么这个不存在?有没有一种方法可以复制这种功能,而不需要做像这样的事情
public function getType()
在每个类中,或者
public function isBirthday()
在event类中。
我在github上找到了这个,但它对我没有用处。我已经对他们的问题发表了评论,看看我是否能得到答案。
发布于 2013-09-12 05:30:46
我同意这个观点,instanceof
不应该出现在模板中。在这种情况下,我使用twig-test
class MyTwigExtension extends TwigExtension
{
public function getTests ()
{
return [
new \Twig_SimpleTest('birthday', function (Event $event) { return $event instanceof Birthday; }),
new \Twig_SimpleTest('walking', function (Event $event) { return $event instanceof Walking; })
];
}
}
在模板中
{% if event is birthday %}{# do something #}{% endif %}
发布于 2013-05-29 18:51:21
如果您知道每个继承的对象都有一个唯一的方法,那么实现这一点的一种间接方法是测试对象的方法。也许你的生日类有一个getBirthday(),而你的Walking类有一个getMap()?
{% if yourobject.methodName is defined %}
//Stuff that should only output when the object in question has the requested method
{% endif %}
发布于 2012-04-12 18:01:03
从架构的角度来看,在模板中使用instanceof是不可取的。如果您发现自己处于“需要”它的位置,那么您可能已经发现了架构中的问题。您的getType解决方案在您的案例中可能是最好的。您仍然可以将其放入事件基类中,并读出实现类的名称。
https://stackoverflow.com/questions/10113442
复制相似问题