Custom Instance of the Mura Scope - Mura Docs v7.1

Custom Instance of the Mura Scope

As a Mura developer, you are going to run into situations from time-to-time where the Mura Scope is not accessible to you. This most often occurs when you're processing logic falls outside of the normal Mura event model (e.g., Ajax requests, accessing your application directly under a non-Mura directory, etc.).

As long as you're working within the realm of the Mura application itself, you can easily create a custom instance of the Mura Scope. One important thing to keep in mind is that you'll most likely want to initialize the Mura Scope with a SiteID.  The reason for this is that most often, you're probably going to to be working with site-specific information, and unless the Mura Scope has been initialized with a SiteID, you won't have access to any site-specific data.

Also, unless a user is accessing your logic directly, and outside of the normal Mura event model, the session scope typically contains a SiteID key. However, there may be rare instances when this does not occur, and when it does, you can always fall back to using the one site that each and every Mura installation includes, which is the "default" site, and its SiteID is always default

Using this knowledge, the examples highlighted below should hopefully make a bit more sense.

Examples

Below is an example of how to create a custom instance of the Mura Scope, checking for an instance of session.siteid, and using that to initialize the Mura Scope, or using the default SiteID, if, for whatever reason, it has not been defined yet.

if ( !IsDefined('m') ) {
  siteid = session.keyExists('siteid') ? session.siteid : 'default';
  m = application.serviceFactory.getBean('m').init(siteid);
}

While the most common method for initializing the Mura Scope is with a SiteID string, it can also be initialized with an event object or a struct that contains a siteid key. 

if ( !IsDefined('m') ) {

  // Assumes you have a pre-defined event object named `yourEventObject`
  m = application.serviceFactory.getBean('m').init(yourEventObject);

  // OR

  yourStruct = {
    siteID = 'SomeSiteID'
    , someKey = 'Some Value'
  };

  m = application.serviceFactory.getBean('m').init(yourStruct);
}