Search code examples
perlmojolicious

How to access other controllers in your application?


I have an application with several controllers dedicated each to its own part, say, "news", "articles" and "shop". They are not connected to each other, but they should be, as I need to insert data from them, like news related to current shop category. I have not found a clean way to access controllers other than the current one that is handling the request.

The structure of the modules is:

  • Site.pm is the main project file.
  • Articles.pm handles articles.
  • News.pm handles news.
  • Shop.pm handles shop.

Site.pm loads each of the above dynamically from an array of module names and calls its register function to set routes up and other things at startup. Articles, news, etc all take content from database, and it is rendered as inline template, thus, I can't just take related news and slam them into the stash, as not all entries in shop might even need that information.


Solution

  • This is a theoretical answer without code.

    You probably have the database stuff decoupled from the actual controllers as models. That's good.

    So let's assume we're in the shop and we want to show news related to the current product. There are at least two ways to do that.

    1. You call your models directly. Your model for news provides a way to get the news for a product. You do that in the shop controller that displays the product page. This controller needs to put the stuff in the stash so the templates can access it.

    2. You create a method in your news controller that is not accessible from the outside. You make it take a product id and find related news articles and populate them into the stash. You forward to it from your product page controller in the shop controller. Afterwards, the product page controller continues. This is the more decoupled way.

    In both cases, your shop template includes another template that knows how to deal with the stuff in the stash for displaying news. You might be able to recycle a news template here.