An idea born in the process of developing our own CMS. Often we need the same events to be accessible simultaneously through the main html view, through ajax, or, for example, through a cell phone. Naturally, it may be necessary not only to output data in different formats(html, JSON, xml), but also to perform additional actions depending on the environment.
You can implement this with conditions in a separate controller method, you can use separate methods for each display type, or you can do it this way…
The idea is to separate controller classes by the way they are mapped.
I.e. we create a basic controller, which implements the default methods for event handling.
Next, for each type of mapping we create a controller, a descendant of the main controller, and implement public methods for events that are available in the given type. Or we make stubs for methods that are not available.
Add a prefix (or postfix) to these controllers’ class names, according to their type. For example: IndexController_Web, IndexController_Ajax, IndexController_Mobile, etc.
Next, in the front controller define in which environment the script is running and what prefix we need to use and call controllers with the right prefix. If the required class doesn’t exist, we load the parent, that way all the default methods will be available.
You can implement in the parent controller only protected methods that implement actions common to all types or return data in a common format. Then you can describe only available methods in the descendants, and unnecessary methods will be unavailable by default.
Pros of this approach :
- The type is only checked once in the front controller and there is no need to check the script conditions each time
- The code is clearly separated and does not get cluttered
- Access the same url in different environments
- Ability to easily close unnecessary methods
I haven’t found any minuses yet)
I think this approach can also be applied to existing CMS like Zend Framework by making small changes in the core or using plugins.