base.controllerModel-View-Controller, or “MVC”, is a well-established paradigm for structuring complex projects.
We all code in Python, and the pythonic way to build web-apps is Django, so let’s look at this from a Django perspective:
models.Modelviews.ViewDjango is good at mapping data between database tables and object-oriented classes in your code. This is about half of Django’s job, and is called an Object Relation Manager, or ORM. The Django Model class is how we use Django’s ORM.
Similarly, Django’s View class is how we use the other half of what Django does, which is an HTTP request/response framework – that is, a web server.
Django even includes some HTML form processing, to help receive back changes to data and communicate them to the model.
But Django shows its limits when we have polymorphic data – where a single Model handles data of related but not identical types.
For example, imagine a Document class that is used to handle various types of documents. Very likely, our Document model has a type field that specifies one of various values, like “HTML Document” vs. “Markdown Document” vs. “Plain Text Document”. Depending on any specific Document’s type, the methods on our model need to branch into very different code paths.
DOCUMENT_TYPES = [
('HTML', 'HTML'),
('MD', 'Markdown'),
('TXT', 'Plain Text'),
]
class Document(models.Model):
doctype = models.CharField(max_length=4, choices=DOCUMENT_TYPES)
# ...other fields...
# ...and methods to manipulate this Document...This is classic polymorphism: all our Documents are stored in the same table, but most every method we might write is going to need a bunch of if-then cases to deal with the different types of documents.
The classic solution to this is a controller.
With controllers, our model is attached to a namespace that has different controllers for different types of documents. We need to have one model, because it’s our interface to the ORM and the database. But with one syntactic step, we can ask any instance of our Document model for its controller, and the correct controller will be selected and returned for whatever type of Document it is.
Using our Enum and Controller classes, our example becomes this:
base.Enum.Define(('DOCUMENT', 'DocumentTypes'), (
('Undefined', None),
('HTML', 'HTML'),
('Markdown', 'MD'),
('Plain Text', 'TXT'),
))
class Document(base.ControllerMixin, models.Model):
CONTROLLER_NAMESPACE = DocumentTypes
CONTROLLER_NAME_PROPERTY = 'type'
type = models.CharField(
max_length = DocumentTypes.MaxTagLength(),
choices = DocumentTypes.Choices()
)
# ...other fields...We also need to define some Controller classes:
class DocumentController(base.Controller): CONTROLLER_NAMESPACE = DocumentTypes # ... methods in common for all documents ... class HTMLDocumentController(DocumentController): CONTROLLER_NAME = DOCUMENT_HTML # ... methods for HTML documents ... class MarkdownDocumentController(DocumentController): CONTROLLER_NAME = DOCUMENT_MARKDOWN # ... methods for Markdown documents ... class TextDocumentController(DocumentController): CONTROLLER_NAME = DOCUMENT_PLAIN_TEXT # ... methods for plain text documents ...
Now whenever we have a Document instance, that instance has an extra property called controller. When we request that controller we get an instance of the specific Controller class that handles that Document’s type:
doc1 = Document() doc1.type = 'HTML' print(doc1.controller) doc2 = Document() doc2.type = 'MD' print(doc2.controller) doc3 = Document() doc3.type = 'TXT' print(doc3.controller)
If done from a python console, this will print something similar to:
<__main__.HTMLDocumentController object at ...> <__main__.MarkdownDocumentController object at ...> <__main__.TextDocumentController object at ...>
That’s it in a nutshell: Instead of trying to implement all our polymorphic logic in one class, we get to split it out to separate classes. The right Controller is picked based on a field on our model.
Each instance of a Controller can refer to the model instance it’s attached to as .item
Additionally, it can also use the slugified name of the class. So in our example above, each controller instance has a .document attribute which is exactly the same as its .item
If you want to change this, the controller may override CONTROLLER_ITEM_NAME:
class DocumentController(base.Controller): CONTROLLER_NAMESPACE = DocumentTypes CONTROLLER_ITEM_NAME = `foobar`
These controllers would have .item and .foobar properties that both refer to the model instance.
The CONTROLLER_NAMESPACE does not need to be an Enum. Anything that supports “in” testing will work, which means you can use even a simple list if you’d like:
MY_DOCUMENT_TYPES = ['HTML', 'MD', 'TXT'] class DocumentController(base.Controller): CONTROLLER_NAMESPACE = MY_DOCUMENT_TYPES
Additionally, we have a trivial base class called ControllerNamespace that we can derive a class from, where sub-classes of that class become our options in the namespace.
If a specific controller can’t be found for an instance of our model, the top-level controller for the namespace will be used.
For instance, if the MarkdownDocumentController did not exist and we had a markdown Document, the top-level DocumentController would be instantiated instead.
It is possible to request a .controller for a model class instead of a class instance. The same logic is followed for finding the right controller to instantiate. The difference is the controller instance’s .item property is given a totally new instance of the model class, rather than a populated instance. (This works only if the model’s __init__ requires no arguments.)
The key takeaway is that the class hierarchy of our controllers is totally separate from the class hierarchy of our models.
The magic look-up table that knows about every controller class is our registry. All controllers need to be registered objects, but deriving from base.Controller usually takes care of this, as it has an auto-register metaclass.