Development:Registry

From OpenLP
Jump to: navigation, search

Registry

The Registry provides global access to registered objects and methods, eliminating the need to pass them in the constructor of the class. This way components do not have to exist when creating an object, but they can be accessed when needed. Before the migration to the Registry the order of class construction was important to allow objects to be available to be passed into dependants. With the Registry this is no longer the case, components need to be built ready to be used.

In addition there have been some convoluted chains of classes to allow one class to see another.

For Example

self.thememanager.mainwindow.renderer.get_main_rectangle(self.theme)

has been replaced with

self.renderer.get_main_rectangle(self.theme)

The registry makes it easier to add the renderer to any class.

Implementation

Registration

To Register a component with the Register requires the following line to be added to a classes constructor

   def __init__(self, parent=None):
       """
       Sets up the foo manager
       """
       QtGui.QWidget.__init__(self, parent)
       Registry().register('foo_manager', self)

This will place the address in the Registry with the reference of foo_manager

Using a Service

To make use of a component is just as simple. Add

   def _get_foo_manager(self):
       """
       Adds the foo_manager to the class dynamically
       """
       if not hasattr(self, '_foo_manager'):
           self._foo_manager = Registry().get(u'foo_manager')
       return self._foo_manager
   foo_manager = property(_get_foo_manager)

To the bottom of your class. This will then allow code to reference self.foo_manager. The reference to the implementation will occur at run time but the code still contain the correct references.