基本接口和类
Zope3选择的一个重要的设计是接口驱动。 接口不仅用于文档也用于适配。 接口是zope3的类型系统。 不像基于类的类型,任何东西都可以实现或者适配它们,并且所有在Zope3系统中正确的代码都应该为一个已知的对象请求一个接口实现。
接口设计被提取出来并超越了基本方法的定义来包括对象schema甚至前/后置条件。 这个数据可以被自省来建立用户接口,这是标准Zope3管理接口得到建立的数量。 事实上,我将在下面的章节中展示这个是怎么做的。
因此,基本的todo应用使用以下接口。 这些只是基本模型对象。 Todo List只是一个仅仅包含实现ITodo接口的项目的容器。 一个Todo除了存储一些简单的数据之外不做其他的事情。 下面就是从todo包里面的interfaces.py文件:
from zope.interface import Interface
import zope.schema
# These will aid in making a special "todo" container by specifying the
# constraint in the interface.
from zope.app.container.constraints import ItemTypePrecondition
from zope.app.container.interfaces import IContained, IContainer
class ITodo(Interface):
""" A todo item doesn"t need to do much... """
description = zope.schema.TextLine(
title=u"To Do",
required=True,
)
details = zope.schema.Text(
title=u"Details",
required=False,
)
done = zope.schema.Bool(title=u"Done")
class ITodoList(IContainer):
""" A todo list contains todo objects. """
def __setitem__(name, object):
""" Add an ITodo object. """
__setitem__.precondition = ItemTypePrecondition(ITodo)
该实现十分简单。 因为这是一个小的应用,所以我将该实现放在了todo/__init__.py里:
from zope.interface import implements
from zope.app.container.btree import BTreeContainer
from persistent import Persistent
from interfaces import ITodoList, ITodo
class TodoList(BTreeContainer):
implements(ITodoList)
class Todo(Persistent):
implements(ITodo)
description = u""
details = u""
done = False
好啦!下面需要做的就是将它配接到Zope3中。但是,你已经能看到这个比在Zope2中写一些数据对象要简单方便多了。