Seb*_*ien 3 plone adapter archetypes plone-4.x
我在Plone 4.3.3下尝试在我的一个产品中自定义原型内容类型的类方法.
我有一个产品bsw.produit_1的内容类型MyContent定义如下:
class MyContent(base.ATCTContent):
implements(IMyContent)
meta_type = "MyContent"
schema = MyContent`
def ma_fonction(self):
......
return res
Run Code Online (Sandbox Code Playgroud)
我想ma_fonction在另一个产品中修改我的功能代码.我尝试过使用适配器并遵循plone文档,但没有成功.
我希望自定义函数的类:
class CustomClass(object):
""" """
implements(IMyContent)
adapts(IMyContent)
def at_post_payment_script(self, obj_transaction):
""" """
......
# My new code
return res
Run Code Online (Sandbox Code Playgroud)
在configure.zcml这里,我宣布我的适配器:
<adapter for="bsw.produit_1.content.mycontent.MyContent"
provides="bsw.produit_1.interfaces.IMyContent"
factory=".customclass.CustomClass" />
Run Code Online (Sandbox Code Playgroud)
在我的ZCML声明,我也试图把archetypes.schemaextender.interfaces.ISchemaExtender作为provides或把接口IMyContent的for,而不是类.
这些都不起作用,每次都不会执行自定义代码.有人有解决方案吗?
您需要的解决方案取决于您想要实现的目标.
但是archetypes.schemaextender是错误的解决方案.schemaextender用于修改架构,包括:
实现自己的adaptera绝对是正确的方法.
首先,您需要为默认行为实现适配器.其次,您需要调整上下文和请求.请求很重要,因为如果您的other产品已安装,这是一种定义更具体的适配器的方法.
默认实现的Python代码(adapter.py):
from zope.component import adapts
from zope.interface import Interface
from zope.interface import implements
class IBehavior(Interface):
def __init__(context, request)
"""Adapts context and request"""
# ... more ...
class DefaultBehavior(object):
implements(IBehavior)
adapts(IMyContent, Interface) # IMPORTAN two discriminators
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
# your default implementation goes here.
Run Code Online (Sandbox Code Playgroud)
使用zcml注册适配器:
<adapter factory=".adapter.DefaultBehavior" />
Run Code Online (Sandbox Code Playgroud)
您现在可以调用默认适配器 ma_fonction
from zope.component import getMultiAdapter
class MyContent(base.ATCTContent)
def ma_fonction(self):
adapter = getMultiAdapter((self, self.REQUEST), IDefaultBehavior)
return adapter()
Run Code Online (Sandbox Code Playgroud)
现在,您可以other使用浏览器层在产品中实现更具体的适配器.检查文档, 如何注册浏览器
在您的other包中,您现在可以注册一个实现相同IBehavior界面的适配器,但也可以调整您的浏览器层.
from other.package.interfaces import IOtherPackageLayer
from zope.component import adapts
from zope.interface import implements
class DifferenBehavior(object):
implements(IBehavior)
adapts(IMyContent, IOtherPackageLayer) # IMPORTAN adapt the browserlayer not Interface
def __init__(self, context, request):
self.context = context
self.request = request
def __call__(self):
# your different implementation goes here.
Run Code Online (Sandbox Code Playgroud)
注册zcml:
<adapter factory=".adapter.DifferenBehavior" />
Run Code Online (Sandbox Code Playgroud)
ma_fonction如果other未安装软件包,您现在调用默认适配器.如果other安装了包,则使用不同的适配器.
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |