Short recipe for adaptation with Five
Wed, Sep 20, 2006,
200 Words
>>> from zope.interface import Interface, Attribute, implements
Let's say we have an object type "Person". This person can introduce himself with the name.
class IPerson(Interface):
name = Attribute('Name of the person')
def say_name():
"""The name of the person"""
class Person(object):
implements(IPerson)
def __init__(self, name):
self.name = name
def say_name():
return 'My name is ' + self.name
Next, we have another object type, let's say "Worker", with an interface of IWorker.
class IWorker(Interface):
job = Attribute('Name of the job')
def set_job():
"""sets the job"""
def say_job():
"""the job"""
Now we want to adapt the Person so that a person is also a Worker.
class PersonJob(object):
implements(IWorker)
def __init__(self, context):
self.context = context
def set_job(self, job):
self.job = job
def say_job(self):
return "My name is %s and I work at %s" % (self.context.name, self.job)
Now let's register the factory that implements the Worker for a Person.
#### >>> registry.register(IPerson, [IWorker,], '', PersonJob)
<configure xmlns="http://namespaces.zope.org/zope">
<adapter
for=".IPerson"
provides=".IWorker"
factory=".PersonJob" />
</configure>
Now let's see how this works
>>> Tom = Person('Tom Sawyer')
>>> print Tom.say_name()
'My name is Tom Sawyer'
>>> tomjob = IWorker(Tom)
>>> tomjob.set_job('DisneyLand')
>>> tomjob.say_job()
'My name is Tom Sawyer and I work at DisneyLand'
Further reference:
- http://plone.org/documentation/tutorial/five-zope3-walkthrough/adapters
- http://codespeak.net/z3/five/manual.html
- http://www.serverzen.net/weblog/archive/2006/09/17/keeping-client-concerns-separate
- http://www.plope.com/Members/chrism/adaptation_for_busy_people
- http://plone.org/documentation/manual/plone-developer-reference/patterns/adapters
- http://svn.zope.org/Zope3/branches/3.3/src/zope/component/README.txt?view=markup
Previous: Basic recipe for a Five view