Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The easiest way would be to pass off value structure to your template renderer. This will keep you from being tempted to doing too much logic within the template itself. </p> <p>For example - First off create an interface for your renderable classes</p> <pre><code>class Renderable { public function getViewData(); } </code></pre> <p>Then make your student and Course classes conform to the interface . </p> <pre><code>class Student implements Renderable{ private $id; private $name; /** * Courses student is attending * @var Course[] */ private $courses = array(); private $numberOfAttendingCourses; public function getViewData(){ $dat = array("id"=&gt;$this-&gt;id, "name"=&gt;$this-&gt;name, "courses"=&gt;array()); foreach($this-&gt;courses as $course){ $dat["courses"][] = $course-&gt;getViewData(); } $dat["numCourses"] = count($dat["courses"]); return $dat; } } class Course implements Renderable{ private $code; private $name; public function fetchViewData(){ return array("code"=&gt;$this-&gt;code, "name"=&gt;$this-&gt;name); } } </code></pre> <p>The create a template parser.</p> <pre><code>class Template { public function render($templateFile, array $data){ if ($data instanceof Renderable){ $data = $data-&gt;getViewData(); } extract ($data); ob_start(); include($templateFile); ob_get_clean(); } } </code></pre> <p>Then a simple template for your markup</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;?= htmlspecialchars($name) ?&gt; (ID: &lt;?= htmlspecialchars($id) ?&gt;) &lt;ul&gt; &lt;?php foreach($courses as $course): ?&gt; &lt;li&gt;&lt;?= htmlspecialchars($course["code"]) ?&gt; (&lt;?= htmlspecialchars($course["code"]) ?&gt;)&lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Then once you have a valid Student object you can simply</p> <pre><code>$template = new Template(); $template-&gt;render("/path/to/template.phtml", $student-&gt;fetchViewData()); </code></pre> <p>This should also make it very simple for you to develop and test your templates as you would be able to use a serviceable array instead of going and creating a Student and a bunch of Course objects. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload