How should partials be loaded when they are dependent on business logic?

kiheiweb

New Member
I'm using the term "partial" to refer to a small section of presentational code which is repeated on many views. For example, a sidebar. In vanilla PHP, where the business and presentation logic is mixed, including a sidebar is no trouble:\[code\]if($someCondition) { include('sidebar.php');}\[/code\]However, in an MVC design pattern, the presentational logic must be kept in the view whilst the business logic must be kept in the controller. If I wish to include a partial unconditionally, then this is unproblematic since I can just have \[code\]include('sidebar.php')\[/code\] in my view. However, I can no longer do so conditionally because that if logic is banned from my view.I have attempted a number of solutions but they all have problems. I am currently using Solution 2:Solution 1Create an include function in my view class which could conditionally include content from my controller. So in my controller I could have the following logic:\[code\]if($someCondition) { $this->view->include('sidebar.php');} $this->view->show('index.php');\[/code\]Problems: sidebar.php will need to be included into index.php at a specific point requiring the include method on the view object to do some sort of parsing.Solution 2Move control of the partials out of the view and put them into the controller:\[code\]if($someCondition) { $this->view->show('header.php', 'sidebar.php', 'index.php', 'footer.php');}else { $this->view->show('header.php', 'index.php', 'footer.php');}\[/code\]Problems: Moves a large portion of the presentational logic into the realm of the controller. It seems to be more natural to me for the view to decide whether or not to include the header. Indeed, every PHP MVC tutorial I can find, has partials under the control of the view and not the controller.Solution 3Duplicate the view and alter the clone so that it includes the sidebar. Then I could conditionally load one or the other in the controller:\[code\]if($someCondition) { $this->view->show('indexWithSidebar.php');}else { $this->view->show('index.php');}\[/code\]Problems: Duplication of code. Consider what would happen if I had 2 sidebars which I needed to be conditionally loaded. Then I would need \[code\]index.php, indexWithSidebar1.php, indexWithSidebar2.php, indexWithSidebar1And2.php\[/code\]. This only gets worse with every condition. Remember that the entire point of taking the sidebar out as a partial was to avoid replicating it anyway and this approach seems to defeat the point.Are any of these solutions the "right" solution and if so, how can I overcome their problems? Is there a better approach out there?
 
Back
Top