Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic layouts in CakePHP

Sorry about the question title, but I couldn't find a more appropriate way to phrase this.

I am currently building a CakePHP powered website and I'm not quite sure how to approach the following issue. The website looks something like the follwing mockup:

Website Mockup .

The greyed out areas are part of the layout, because their content does not change between views. In the sidebar, I have a collection of ads who are linked to several models. I need controller logic to determine the picture associated with an ad. Also, the ad list needs to be dynamic. Where should I put the logic for building the sidebar?

I've thought about:

  • putting the logic into the AppController (beforeFilter / afterFilter) - the problem is I can't use the controller logic I need (the other controllers inherit from AppController, I'm not sure how to use them there).
  • making a component - is it okay to build components that rely on controllers?
  • replicating the sidebar code in all controllers that render views - this seems kind of stupid to me.

What is the Cake way for this?


Update

After some reading and experimenting, I've gotten to refactoring most of it.

I obtained the best performance by moving the logic for building my ads in the model (eliminating the component that retrieved the pictures) and not using requestAction. It's almost three times faster and the code looks much better.

like image 822
Alex Ciminian Avatar asked Sep 02 '25 09:09

Alex Ciminian


1 Answers

I've done something similar for data-driven navigation. I put my logic in AppController::beforeRender and haven't had any problems. I'm not sure I understand your concern related to controller inheritance. I retrieve my menus via:

$menus = $this->NavMenuItem->groupByMenu();
$this->set( compact( 'menus' ) );

I then created an element that renders the menu. It's executed by the layout via:

<?php echo $this->element( 'navigation', array( 'id' => 'secondary', 'menu' => $menus['SECONDARY'] ) ) ?>

If that doesn't help, maybe you can further explain your issue with controller inheritance in a comment.

like image 65
Rob Wilkerson Avatar answered Sep 05 '25 00:09

Rob Wilkerson