ユーティリティー

はじめに

ユーティリティークラスはサイト全体に対して便利な機能を提供します。 マーカーインターフェースによって登録されます。 サイト設定またはアドオンプロダクトは機能を強化するためにユーティリティーを上書きできます。

詳細は以下を参照してください。

ユーティリティーを登録する

ユーティリティーは Plone が起動して ZCML を読み込むときに構築されます。 ユーティリティーはコンストラクタの引数を利用できません。 コンテクストやリクエストのような引数を使用したい場合は、その代わりに view かアダプターを使用することを考えてください。 ユーティリティーには名前が付いていたり、付いていなかったりします。

ZCML の例です。:

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

Python の例(名前付きユーティリティー):

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

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

ユーティリティーを取得する

二つの関数があります。

  • zope.component.getUtility はユーティリティーが見つからない場合に例外が発生します。
  • zope.component.queryUtility はユーティリティーが見つからない場合に None を返します。

例:

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)

ノート

Zope コンポーネントアーキテクチャーがまだ初期化されていないため、 import の間はモジュールの本文レベルのコードでは getUtility() は使用できません。

インターフェースから全名前付きユーティリティーを取得する

zope.component.getUtilitiesFor() を使用します。

以下は使用例です。

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