In a well-designed WebObjects application, Enterprise Object classes don’t have direct knowledge of WebObjects classes. In practical terms, this means that Enterprise Objects classes don’t reference any classes in the WebObjects framework (com.webobjects.appserver). Enterprise Object classes designed this way are more portable and help you achieve the promise of reusable, highly maintainable business objects.
However, there are occasions in which you need to reference a WebObjects object such as WOSession or WOApplication. There is no direct API to do this. However, there are a few tricks that are commonly used to accomplish this.
The easiest way to access a WOSession object in an Enterprise Object class is to set the delegate of an editing context to be the session object. When you invoke the method editingContext on an enterprise object instance, it returns the Session’s default editing context (this is the default behavior; your configuration may differ, depending on customizations you make).
Assuming your enterprise object classes use the default editing context configuration, to set the delegate for the editing context of any enterprise object class in your application, you invoke defaultEditingContext().setDelegate(this) in your Session class’s constructor. Then, to get a reference to the Session object in an enterprise object class, you invoke the method shown in “Listing A-1” on an enterprise object instance.
Listing A-1 Accessing a Session object from an enterprise object
Session aSession = (Session)editingContext().delegate(); |
The code in “Listing A-1” assumes that an enterprise object’s editing context is not null and that the enterprise object is in the editing context. In an enterprise object’s constructor, this is not necessarily the case: The enterprise object may not yet be inserted into the editing context. So, the safe place to invoke the code is in awakeFromInsertion or awakeFromFetch.
While this is the easiet way to obtain references to WebObjects objects from enterprise objects, it compromises the purity and portability of the enterprise objects. A better approach would be to use notifications to access WebObjects objects from within enterprise objects. This approach maintains the decoupling between the two frameworks.
Last updated: 2007-07-11