Substitutions
Substitutions allow you to override existing methods in a base class that you cannot modify (for example, the source comes from an external dependency). As a result, Dari substitutes the new methods for the original methods everywhere the base class is used.
A substitution implements the Substitution interface, and it extends the class for which you want to substitute methods. Substitution implementations do not change the underlying parent classes.
The following substitution example changes the behavior of the base com.psddev.dari.db.Record#getLabel
method for com.psddev.cms.db.Site
objects. The base getLabel
method returns the name of the site. The substitution method returns the name of the site, plus an indication of the site's global access.
public class SiteSubstitution extends Site implements Substitution {
@Override
public String getLabel() {
boolean isGlobal = as(Site.ObjectModification.class).isGlobal();
String label = super.getLabel();
return isGlobal == true
? label + " (Can be accessed globally)"
: label + " (Cannot be accessed globally)";
}
-
Gets the value of the
isGlobal
flag. Because this flag was added to the originalSite
class via a system modification,isGlobal
is accessed using the State.as method. -
Gets the label of the site. As a subclass of
Site
,SiteSubstitutions
can call super methods. -
Returns the site name plus a parenthetical text string that indicates the site's global access status.
The label appears in the Brightspot Sites widget.
Substitutions tell Dari to return the child substitution object whenever an instance of the parent class is requested in the code. In the example above, Dari returns SiteSubstitution
whenever code retrieves an instance of Site
.
Substitution only applies when retrieving existing objects. Substitution does not apply to creating new objects. For example, creating a new Site
does not create a new SiteSubstitution
object.
See also: