tags:

views:

101

answers:

2

I'm developing a application with CakePHP, and I have two layouts: one for the home page, and another for the rest of the application. Except for some coding on the header, they're almost exactly the same. Is there something I can do to keep DRY, without using IFs all over the layout?

+1  A: 

Define an interface to a layout type. Every place you have an "if layout main" or "if layout other" define an interface function

interface IMyLayout
{
    function DrawArea1(...)
    ...
}

class CMyMainLayout implements IMyLayout
{
    function DrawArea1()
    {
        //... draw area 1 for main
    }
    ...
}


class CMyOtherLayout implements IMyLayout
{
    function DrawArea1()
    {
        //... draw area 1 for other
    }
}

Then you just select one or the other by newing the correct object

 if ($main)
 {
     $layout = new CMyMainLayout;
 }
 else
 {
     $layout = new CMyOtherLayout;
 }

 $layout->DrawArea1();
Doug T.
I'm not sure about interfaces, but I like the idea!
Julio Greff
+5  A: 

I'd suggest using a ton of elements. This way, you can still keep all of the code in one place. For example, if this is your home page layout (boilerplate excluded):

<body>
     <?php echo $this->renderElement('pageHeader'); ?>
     <?php echo $this->renderElement('frontPageNotification'); ?>
     <?php echo $this->renderElement('navAndOtherStuff'); ?>
     ...
</body>

And this is your interior layout (where you want to display everything except for the frontPageNotification stuff:

<body>
     <?php echo $this->renderElement('pageHeader'); ?>
     <?php echo $this->renderElement('navAndOtherStuff'); ?>
     ...
</body>

Now, if they're almost exactly alike, I would probably just use a single layout and have a few if statements within the layout itself to determine what's to be displayed. Also, you can choose which elements get displayed by looking at the $this->params array to figure out which controller and action is behind the page being loaded. Like:

<body>
     <?php echo $this->renderElement('pageHeader'); ?>

     <?php if($this->params['controller'] == 'pages' && $this->params['action'] == 'index') { echo $this->renderElement('frontPageNotification'); } ?>
     <?php echo $this->renderElement('navAndOtherStuff'); ?>
     ...
</body>

Which is, admittedly, rather ugly. Just trying to present all the options I could think of :)

Good luck

inkedmn
In cake 1.2 it's just echo $this->element(); not renderElement
neilcrookes
I'd never heard of that, actually (and echo $this->renderElement() works just fine in 1.2) :)
inkedmn
Actually, I've never used renderElement(), element() works just fine!
Julio Greff