2. The Registry, selectors and application objects#
This chapter deals with some of the core concepts of the CubicWeb framework which make it different from other frameworks (and maybe not easy to grasp at a first glance). To be able to do advanced development with CubicWeb you need a good understanding of what is explained below.
This chapter goes deep into details. You don’t have to remember them all but keep it in mind so you can go back there later.
An overview of AppObjects, the VRegistry and Selectors is given in the Registries and application objects chapter.
the first level key returns a registry. This key corresponds to the __registry__ attribute of application object classes
the second level key returns a list of application objects which share the same identifier. This key corresponds to the __regid__ attribute of application object classes.
A registry holds a specific kind of application objects. There is for instance a registry for entity classes, another for views, etc…
CWRegistryStore has two
being the access point to all registries
handling the registration process at startup time, and during automatic reloading in debug mode.
2.1.1. Details of the recording process#
On startup, CubicWeb loads application objects defined in its library and in cubes used by the instance. Application objects from the library are loaded first, then those provided by cubes are loaded in dependency order (e.g. if your cube depends on an other, objects from the dependency will be loaded first). The layout of the modules or packages in a cube is explained in Standard structure for a cube.
For each module:
by default all objects are registered automatically
if some objects have to replace other objects, or have to be included only if some condition is met, you’ll have to define a registration_callback(vreg) function in your module and explicitly register all objects in this module, using the api defined below.
Once the function registration_callback(vreg) is implemented in a module, all the objects from this module have to be explicitly registered as it disables the automatic objects registration.
2.1.2. API for objects registration#
Here are the registration methods that you can use in the
registration_callback to register your objects to the
CWRegistryStore instance given as argument (usually named
# register everything in the module except SeeAlsoComponent
vreg.register_all(globals().itervalues(), __name__, (SeeAlsoVComponent,))
# conditionally register SeeAlsoVComponent
if 'see_also' in vreg.schema:
In this example, we register all application object classes defined in the module except SeeAlsoVComponent. This class is then registered only if the ‘see_also’ relation type is defined in the instance’schema.
# replace AuthenticationManager by GAEAuthenticationManager
# replace PersistentSessionManager by GAEPersistentSessionManager
In this example, we explicitly register classes one by one:
the SessionCleaner class
the GAEAuthenticationManager to replace the AuthenticationManager
the GAEPersistentSessionManager to replace the PersistentSessionManager
If at some point we register a new appobject class in this module, it won’t be registered at all without modification to the registration_callback implementation. The previous example will register it though, thanks to the call to the register_all method.
2.1.3. Runtime objects selection#
Now that we have all application objects loaded, the question is : when I want some specific object, for instance the primary view for a given entity, how do I get the proper object ? This is what we call the selection mechanism.
As explained in the The Core Concepts of CubicWeb section:
each application object has a selector, defined by its __select__ class attribute
this selector is responsible to return a score for a given context
0 score means the object doesn’t apply to this context
else, the higher the score, the better the object suits the context
the object with the highest score is selected.
When no single object has the highest score, an exception is raised in development mode to let you know that the engine was not able to identify the view to apply. This error is silenced in production mode and one of the objects with the highest score is picked.
In such cases you would need to review your design and make sure your selectors or appobjects are properly defined. Such an error is typically caused by either forgetting to change the __regid__ in a derived class, or by having copy-pasted some code.
For instance, if you are selecting the primary (__regid__ = ‘primary’) view (__registry__ = ‘views’) for a result set containing a Card entity, two objects will probably be selectable:
the default primary view (__select__ = is_instance(‘Any’)), meaning that the object is selectable for any kind of entity type
the specific Card primary view (__select__ = is_instance(‘Card’), meaning that the object is selectable for Card entities
Other primary views specific to other entity types won’t be selectable in this case. Among selectable objects, the is_instance(‘Card’) selector will return a higher score since it’s more specific, so the correct view will be selected as expected.
2.1.4. API for objects selections#
Here is the selection API you’ll get on every registry. Some of them, as the ‘etypes’ registry, containing entity classes, extend it. In those methods, *args, **kwargs is what we call the context. Those arguments are given to selectors that will inspect their content and return a score accordingly.
2.2. The AppObject class#
2.3. Predicates and selectors#
Predicates are scoring functions that are called by the registry to tell whenever an appobject can be selected in a given context. Predicates may be chained together using operators to build a selector. A selector is the glue that tie views to the data model or whatever input context. Using them appropriately is an essential part of the construction of well behaved cubes.
Of course you may have to write your own set of predicates as your needs grows and you get familiar with the framework (see Defining your own predicates).
A predicate is a class testing a particular aspect of a context. A selector is built by combining existant predicates or even selectors.
2.3.1. Using and combining existant predicates#
You can combine predicates using the &, | and ~ operators.
When two predicates are combined using the & operator, it means that both should return a positive score. On success, the sum of scores is returned.
When two predicates are combined using the | operator, it means that one of them should return a positive score. On success, the first positive score is returned.
You can also “negate” a predicate by precedeing it by the ~ unary operator.
Of course you can use parenthesis to balance expressions.
The goal: when on a blog, one wants the RSS link to refer to blog entries, not to the blog entity itself.
To do that, one defines a method on entity classes that returns the
RSS stream url for a given entity. The default implementation on
AnyEntity (the generic entity class used
as base for all others) and a specific implementation on Blog will
do what we want.
But when we have a result set containing several Blog entities (or different entities), we don’t know on which entity to call the aforementioned method. In this case, we keep the generic behaviour.
Hence we have two cases here, one for a single-entity rsets, the other for multi-entities rsets.
In web/views/boxes.py lies the RSSIconBox class. Look at its selector:
''' just display the RSS icon on uniform result set '''
__select__ = box.Box.__select__ & non_final_entity()
It takes into account:
the inherited selection criteria (one has to look them up in the class hierarchy to know the details)
non_final_entity, which filters on result sets containing non final entities (a ‘final entity’ being synonym for entity attributes type, eg String, Int, etc)
This matches our second case. Hence we have to provide a specific component for the first case:
'''just display the RSS icon on uniform result set for a single entity'''
__select__ = RSSIconBox.__select__ & one_line_rset()
Here, one adds the
one_line_rset predicate, which
filters result sets of size 1. Thus, on a result set containing multiple
one_line_rset makes the EntityRSSIconBox class non
selectable. However for a result set with one entity, the EntityRSSIconBox
class will have a higher score than RSSIconBox, which is what we wanted.
Of course, once this is done, you have to:
fill in the call method of EntityRSSIconBox
provide the default implementation of the method returning the RSS stream url on
redefine this method on Blog.
2.3.3. When to use selectors?#
Selectors are to be used whenever arises the need of dispatching on the shape or content of a result set or whatever else context (value in request form params, authenticated user groups, etc…). That is, almost all the time.
Here is a quick example:
'''if the user is the anonymous user, build a link to login else a link
to the connected user object with a logout link
__regid__ = 'loggeduserlink'
# display login link
# display a link to the connected user object with a loggout link
The proper way to implement this with CubicWeb is two have two different classes sharing the same identifier but with different selectors so you’ll get the correct one according to the context.
'''display a link to the connected user object with a loggout link'''
__regid__ = 'loggeduserlink'
__select__ = component.Component.__select__ & authenticated_user()
# display useractions and siteactions
'''build a link to login'''
__regid__ = 'loggeduserlink'
__select__ = component.Component.__select__ & anonymous_user()
# display login link
The big advantage, aside readability once you’re familiar with the system, is that your cube becomes much more easily customizable by improving componentization.
2.3.4. Defining your own predicates#
You can use the
decorator to easily write your own predicates as simple python
In other cases, you can take a look at the following abstract base classes:
2.3.5. Debugging selection#
Once in a while, one needs to understand why a view (or any
application object) is, or is not selected appropriately. Looking at
which predicates fired (or did not) is the way. The
context manager to help with that, if you’re running your instance in
2.4. Base predicates#
Here is a description of generic predicates provided by CubicWeb that should suit most of your needs.
2.4.1. Bare predicates#
Those predicates are somewhat dumb, which doesn’t mean they’re not (very) useful.
2.4.2. Result set predicates#
Those predicates are looking for a result set in the context (‘rset’ argument or the input context) and match or not according to its shape. Some of these predicates have different behaviour if a particular cell of the result set is specified using ‘row’ and ‘col’ arguments of the input context or not.
2.4.3. Entity predicates#
Those predicates are looking for either an entity argument in the input context, or entity found in the result set (‘rset’ argument or the input context) and match or not according to entity’s (instance or class) properties.
2.4.4. Logged user predicates#
Those predicates are looking for properties of the user issuing the request.
2.4.5. Web request predicates#
Those predicates are looking for properties of web request, they can not be used on the data repository side.
2.4.6. Other predicates#
You’ll also find some other (very) specific predicates hidden in other modules