I am creating breadcrumbs on my simple site.
I have some helper classes. I use them like this (just example):
$Breadcrumbs = new Breadcrumbs();
$Breadcrumbs->add(new Breadcrumb("/", "page1"));
$Breadcrumbs->add(new Breadcrumb("/", "page2"));
$Breadcrumbs->add(new Breadcrumb("/", "page3"));
$breadcrumb->show();
returns this:
<ol class="breadcrumb">
<li><a href="/">page1</a></li>
<li><a href="/">page2</a></li>
<li class="active">page3</li>
</ol>
So, in my project I have some switch-case
constructions in which I include some files. In this files I am using $breadcrumbs->add(...)
. This code:
<div class="container body">
<? $Breadcrumbs->show();?>
<?
$page = isset($_GET['page']) ? $_GET['page'] : null;
switch($page):
case "suppliers":
require_once($DOCUMENT_ROOT."/modules/suppliers.php");
break;
default:
require_once($DOCUMENT_ROOT."/modules/default.php");
break;
endswitch;
?>
<? $Breadcrumbs->show();?>
</div>
gives me this result:
Well, it works like it must work. I am using $breadcrumbs->add(...)
in require files after I called $breadcrumb->show()
first time thats why 1st call returns blank result. 2nd call of show()
is after all breadcrumbs are added, so it returns fine result.
The questions is how to output breadcrumbs before switch
blocks but with right content. Maybe I need a buffer or idk?
This is a good example of why it is such a good idea to separate out logic from presentation: you have a nice abstraction for crumb links, but can't use it properly because your other code is outputting as it goes along, rather than working with abstract data.
Obviously, you could throw away your current structure and port both logic and display directly into a new framework, but assuming you want to migrate from where you are now, here's one approach:
echo
or ?>
with concatenation to a string called something like $results['generic_output']
. This is effectively like buffering your output, and is enough to let you use your existing abstractions like $breadcrumbs
at any time. At this stage, your "template" would consist mostly of echo $results['generic_output']
, plus the boilerplate header and footer which is probably already gathered in one place.$results['sidebar_content']
with just the content of that sidebar; the boilerplate to lay it out can then go into your template, and you've reduced the amount of code duplication.I would like to stress that this is not the way to a perfect framework, or the definitive solution to your situation, but it's one way of organising existing code (and existing thinking) in the right direction.
In the above, the "templates" could just be a set of PHP files using ?>
or echo
to produce the output, or it could be a dedicated templating system such as Smarty or Twig. Indeed, the point of the separation is that you could change your mind on that front later, because the result of the code modules would be an array of data to be displayed, which is just what Smarty or Twig would need as input.