3

我一直在使用没有问题的模式行为,但我也想有一个提供一些逻辑的方法。现在我有

class IMyFoo(form.Schema):
    requester = schema.TextLine(title=_(u"Requestor"),
              required=False,
          )

    def foo(self):
      """ foo """

alsoProvides(IMyFoo, IFormFieldProvider)

而在zcml

<plone:behavior
    title="My behavior"
    description="Some desc"
    provides=".behaviors.IMyFoo"
    for=".interfaces.ISomeInterface"
    />

我在 portal_types 的内容类型的行为部分中包含了 IMyFoo。这给了我架构,但不是那个 foo() 方法。因此,我尝试使用以下代码通过阅读http://plone-training.readthedocs.org/en/latest/behaviors2.html为其添加工厂

class MyFoo(object):    
    def foo(self):
      return 'bar'

而在zcml

<plone:behavior
    title="My behavior"
    description="Some desc"
    provides=".behaviors.IMyFoo"
    factory=".behaviors.MyFoo"
    for=".interfaces.ISomeInterface"
    />

但这似乎没有什么不同,或者至少,我不知道如何访问该方法。我能来的最接近的是以下内容:

class IMyFoo(Interface):
  """ Marker """

class MyFoo(object):

  def __init__(self, context):
      self.context = context

  def foo(self):
    return 'bar'

<adapter for=".interfaces.ISomeInterface"
     factory=".behaviors.MyFoo"
     provides=".behaviors.IMyFoo" />

我将 IMyFoo 放在 fti 的行为属性中,然后通过遍历所有行为来调用它

behavior = resolveDottedName(context.portal_types.getTypeInfo(context.portal_type).behaviors[-1]))
behavior(self).myfoo()

当然,像这样通过 FTI 并不是正确的做法。但我在这一点上不知所措。在 Archetypes 中,我只需要创建一个 mixin 类并使用我想使用的任何内容类型来继承它。我可以在这里做同样的事情,但我的理解是行为应该是它们的替代品,所以我想弄清楚如何使用这种首选方法。

4

1 回答 1

6

正如您所发现的,模式类实际上只是一个接口。它不能提供任何方法。为了提供更多功能,您需要将您的行为接口连接到一个工厂类,该类适应一个敏捷对象来提供您的接口。

所以,如果你的 behavior.py 看起来像这样:

# your imports plus:
from plone.dexterity.interfaces import IDexterityContent
from zope.component import adapts
from zope.interface import implements

class IMyFoo(form.Schema):
    requester = schema.TextLine(
      title=_(u"Requestor"),
      required=False,
      )

    def foo(self):
      """ foo """

alsoProvides(IMyFoo, IFormFieldProvider)

class MyFoo(object):    
    implements(IMyFoo)
    adapts(IDexterityContent)

    def __init__(self, context):
        self.context = context

    def foo(self):
      return 'bar'

那么你唯一的 zcml 声明将是:

<plone:behavior
    title="My behavior name"
    description="Behavior description"
    provides=".behavior.IMyFoo"
    factory=".behavior.MyFoo"
    for="plone.dexterity.interfaces.IDexterityContent"
    />

而且,您将使用以下代码实现您的方法:

IMyFoo(myFooishObject).foo()

请注意 IDExterityContent 的使用。您正在创建一种可以应用于任何敏捷内容的行为。因此,行为适配器应该用于那个非常通用的接口。

于 2015-01-31T01:13:13.047 回答