Utilities

Utility classes provide site-wide utility functions. They are registered by marker interfaces. Site customization logic or add-on products can override utility for enhanced functionality.

Read more in zope.component documentation.

Register utility

Utility is constructed when Plone is started and ZCML is read. Utilities take no constructor parameters. If you need to use parameters like context or request, consider using views or adapters instead. Utilities may or may not have a name.

ZCML example:

<!-- Register header animation picking logic - override this for your custom logic -->
<utility
  provides="plone.app.headeranimation.interfaces.IHeaderAnimationPicker"
  factory=".picker.RandomHeaderAnimationPicker" />

Python example (named utility):

def registerOnsitePaymentProcessor(processor_class):
    """ """

    # Make OnsitePaymentProcessor class available as utiltiy
    processor = processor_class()
    gsm = component.getGlobalSiteManager()
    gsm.registerUtility(processor, interfaces.IOnsitePaymentProcessor, processor.name)

Getting utility

There are two functions

  • zope.component.getUtility will raise exception if utility is not found
  • zope.component.queryUtility will return None if utility is not found

Utility query parameters are passed to the utility class constructor.

Example:

from zope.component import getUtility, queryUtility

# context and request are passed to the utility class constructor
# they are optional and depend on the utility itself
picker = getUtility(IHeaderAnimationPicker, context, request)

Getting all named utilities of one interface

Use zope.component.getUtilitiesFor().

Example

def OnsitePaymentProcessors(context):
    """ List all registered on-site payment processors.

    Mostly useful for validating form input.

    Vocabulary contains all payment processors, not just active ones.

    @return: zope.vocabulary.SimpleVocabulary
    """
    utilities = component.getUtilitiesFor(interfaces.IOnsitePaymentProcessor)
    for name, instance in utilities:
        pass

Table Of Contents

Previous topic

Adapters

Next topic

GenericSetup and profiles

This Page