****** Отредактировано **** (добавлено решение mvc)
Не засоряйте свой код ненужными функциями, частями и т. Д. Зачем беспокоиться о HTML с самого начала, когда вы можете создавать свои данные, , а затем преобразуйте их в таблицу HTML? Вот пример MVC (в следующем коде предполагается, что проект с одним модулем называется default), измените его соответствующим образом, если проект основан на модуле):
[список 1] приложение / контроллер / IndexController.php
class IndexController extends Zend_Controller_Action {
public function indexAction() {
$this->view->calData = new Default_Model_Calendar('2010-07-17');
}
}
[листинг 2] приложение / модели / Calendar.php
class Default_Model_Calendar {
/* @var Zend_Date */
private $_date;
/* @param Zend_Date|string|int $date */
public function __construct($date) {
$this->_date = new Zend_Date($date);
}
/* @return Zend_Date */
public function getTime() {
return $this->_date;
}
public function getData() {
// normally, fetch data from Db
// array( day_of_month => event_html, ... )
return array(
1 => 'First day of month',
4 => '<span class="holiday">Independence Day</span>',
17 => '<img src="path/to/image.png" />'
//...
);
}
}
[lisging 3] application / view / scripts / index / index.phtml
echo $this->calendarTable($this->calData);
[листинг 4] приложение / представление / помощники / CalendarTable.php
class Default_View_Helper_CalendarTable extends Zend_View_Helper_Abstract {
private $_calData;
public function calendarTable($calData = null) {
if (null != $calData) {
$this->_calData = $calData;
}
return $this;
}
public function toString() {
$curDate = $this->_calDate->getTime();
$firstDay = clone $curDate(); // clone a copy to modify it safely
$firstDay->set(Zend_Date::DAY, 1);
$firstWeekDay = $firstDay->get(Zend_Date::WEEKDAY);
$numDays = $curDate->get(Zend_Date::MONTH_DAYS);
// start with an array of empty items for the first $firstweekDay of the month
$cal = array_fill(0, $firstweekDay, ' ');
// fill the rest of the array with the day number of the month using some data if provided
$calData = $this->_calData->getData();
for ($i=1; $i<=$numDays; $i++) {
$dayHtml = '<span class="day-of-month">' . $i . '</span>';
if (isset($calData[$i])) {
$dayHtml .= $calData[$i];
}
$cal[] = $dayHtml;
}
// pad the array with empty items for the remaining days of the month
//$cal = array_pad($cal, count($cal) + (count($cal) % 7) - 1, ' ');
$cal = array_pad($cal, 42, ' '); // OR a calendar has 42 cells in total...
// split the array in chunks (weeks)
$calTable = array_chunk($cal, 7);
// for each chunks, replace them with a string of cells
foreach ($calTable as & $row) {
$row = implode('</td><td>', $row);
}
// finalize $cal to create actual rows...
$calTable = implode('</td></tr><tr><td>', $calTable);
return '<table class="calendar"><tr><td>' . $calTable . '</td></tr></table>';
}
public function __toString() {
return $this->__toString();
}
}
С помощью этого кода вы можете даже установить то, что вам нужно в массиве $cal
, прежде чем вызывать array_chunk
для него. Например, $cal[] = $dayHtml . '<a href="#">more</a>';
Это также следует истинному MVC, поскольку данные (в Default_Model_Calendar
) и представление (в Default_View_Helper_CalendarTable
) полностью разделены, что дает вам свободу использовать любую другую модель с помощником вида или просто не использовать никакой помощник вида с твоя модель!