[Zope3-dev] Re: Newbie questions.

Philipp von Weitershausen philipp at weitershausen.de
Mon Jun 28 02:31:56 EDT 2004


Joao Paulo,

> For instance, let's pretend I have two interfaces.  IState, that 
> represents a state, and ICity, that represents a city.  They have a 
> 1-to-many relationship, where a state can contain any number of cities, 
> and a city belongs to only one state (very basic, like I said).
> Accordingly, I'd like to have an attribute at ICity called state, that 
> is a IState.  But when I'm adding a new city, how can I make a lookup of 
> the available states?  I'd like to enforce that the city must belong to 
> one of the available states.  How can one enforce that kind of requisite 
> in Zope3?  How can I make a list of the available states?

States would be named utilities. Utilities are small components that can 
be looked up only by interface or by interface and name; in the latter 
case, we speak of named components. The name of the utility in this case 
could be its two letter abbreviation:

Let's start by firing up all the essential Zope services. Make sure that 
you have Zope3/src in your python path and that your current directory 
is your instance home where site.zcml is:

   >>> from zope.app.debug import Debugger
   >>> app = Debugger()

Let's say IState was your interface which would allow a string 
representation (__str__)

   >>> from zope.interface import Interface
   >>> class IState(Interface):
   ...     def __str__():
   ...         """Return the name of the state"""

Let's be lazy and subclass Python's string (str) in the implementation:

   >>> from zope.interface import implements
   >>> class State(str):
   ...     implements(IState)

Now, we can make new states:

   >>> massachusetts = State("Massachusetts")
   >>> california = State("California")

and register them with the utility service:

   >>> from zope.app import zapi
   >>> utility_service = zapi.getService('Utilities')

   >>> utility_service.provideUtility(IState, massachusetts, 'MA')
   >>> utility_service.provideUtility(IState, california, 'CA')

Then, if we want to know which states are available, we ask for all 
utilities providing IState. We of course expect our two states to be 
returned:

   >>> for name, state in utility_service.getUtilitiesFor(IState):
   ...     print "'%s' is registered as '%s'" % (name, state)
   ...
   'CA' is registered as 'California'
   'MA' is registered as 'Massachusetts'

Maybe you would like to write a bit more text for this example and 
publish it as a "utilities" howto. I think people would appreciate that.

> I think I could model IState subclassing IContainer, and put the cities 
> inside each state container.

Containers are indeed a good way to express containment relationships. 
Note that an object can only be contained once, though. The same object 
cannot be contained in two different containers at the same time.

Philipp



More information about the Zope3-dev mailing list