Вы не зашли.
Главная » PHP » Функция навигации по страницам
#41. tipsun Off (19)
Moderator
2011.12.11 21:09
Так бы сразу. Спс.
Добавлено спустя   6 минут  26 секунд:
Я уже и забыл, что так метод вызвать можно big_smile
Мда, жестко я туплю...
Отредактировано tipsun (2011.12.11 22:10)
#42. tipsun Off (19)
Moderator
2011.12.12 16:04
Код:
span style="color: #0000BB"><?phpclass pageMan { private $_method = null, $_count = null, $_page = null, $_tmpPage = 1, $_pages = null, $_start = null; private static $_items = 10; /** * pageMan::__construct() * Обработка входящих данных в класс. * @param mixed $method * @param mixed $count * @param mixed $page * @param mixed $items * * @return void */ public function __construct($method, $count, $page, $items=null) { if (method_exists(__CLASS__, '_method' . $method)) { $this->_method = '_method' . $method; } else { trigger_error('Nonexistent method', E_USER_ERROR); } if (is_numeric($count) and 0 < $count) { $this->_count = (int)$count; } else { trigger_error('Value must be integer', E_USER_ERROR); } if (is_numeric($page) and 0 < $page) { $this->_tmpPage = (int)$page; } if (is_numeric($items)) { if (0 < $items) $this->_items = (int)$items; else $this->_items = $this->_count; } else { $this->_items = self::$_items; } } /** * pageMan::_countPages() * Расчет общего кол-ва страниц. * @return integer */ private function _countPages() { if (null === $this->_pages) { $this->_pages = ceil($this->_count / $this->_items); } return $this->_pages; } /** * pageMan::getPages() * Получение общего числа страниц. * @return integer */ public function getPages() { return call_user_method('_countPages', $this); } /** * pageMan::_setPage() * Коррекция указанной/текущей страницы. * @return integer */ private function _setPage() { if (null === $this->_page) { $this->_page = min($this->_tmpPage, $this->_countPages()); } return $this->_page; } /** * pageMan::getPage() * Получение корректной текущей страницы. * @return integer */ public function getPage() { return $this->_setPage(); } /** * pageMan::_setStart() * Расчет начальной точки отсчета показа записей в вашем цикле. * @return integer */ private function _setStart() { if (null === $this->_start) { $this->_start = ($this->_setPage() - 1) * $this->_items; } return $this->_start; } /** * pageMan::getStart() * Получение начальной точки отсчета показа записей в цикле. * @return integer */ public function getStart() { return $this->_setStart(); } /** * pageMan::_methodArray() * Расчет конечной точки отсчета показа записей в цикле для массива данных. * @return integer */ private function _methodArray() { return min(($this->_setStart() + $this->_items), $this->_count); } /** * pageMan::_methodTable() * Расчет конечной точки отсчета показа записей в цикле для данных в таблице (DB). * @return integer */ private function _methodTable() { return $this->_items; } /** * pageMan::getStop() * Получение конечной точки отсчета показа записей в цикле. * @return integer */ public function getStop() { return call_user_method($this->_method, $this); } /** * pageMan::prevPage() * Получение номера предыдущей страницы. * @return integer */ public function prevPage() { if (null === $this->_page) { $this->_setPage(); } return 1 < $this->_page ? $this->_page - 1 : $this->_page; } /** * pageMan::nextPage() * Получение номера следующей страницы. * @return integer */ public function nextPage() { if (null === $this->_pages) { $this->_countPages(); } if (null === $this->_page) { $this->_setPage(); } return $this->_pages > $this->_page ? $this->_page + 1 : $this->_page; } }?>
Вот... первые шаги к ::10 11 [12] 13 14::

Код:
span style="color: #0000BB"><?php$pageNum = 5;$pg = new pageMan('array', 1768, $pageNum);define('NOWPAGE', $pg->getPage());define('ALLPAGES', $pg->getPages());for ($i=-4; $i<=4; $i++) { $page = NOWPAGE + $i; if (NOWPAGE == $page) { printf('[%d] ', $page); continue; } if (1 <= $page and ALLPAGES >= $page) { printf('%d ', $page); } }?>
Наверно все-таки придется делать в классе отдельный метод и возвращать массив.
А то в шаблоне столько катать каждый раз не то.
А в шаблоне уже сделать еще foreach() цикл и закреплять там ссылки.

Хотя по идее можно было бы принять этот адрес,
обработать htmlspecialchars() и нормально, наверно.
Отредактировано tipsun (2011.12.12 16:04)
#43. tipsun Off (19)
Moderator
2011.12.12 18:06
Еще чтоб в холостую циклы не гонять, можно заранее наверно расчитать количество повторений.
Отредактировано tipsun (2011.12.12 19:07)
#44. Gemorroj Off (107)
Administrator
2011.12.12 19:07
Сам интерфейс класса не нравится.
* @param mixed $method
         * @param mixed $count
         * @param mixed $page
         * @param mixed $items

new pageMan('array', 1768, $pageNum);
откуда я узнаю что 1 параметром нужно передать строку array ? O_o
и так же про остальные параметры.

Продумай сначала как внешне твой класс будет работать.
Например, удобно было бы как-то так:
Код:
span style="color: #0000BB"><?php$obj = new pageMan();// задаем настройки$obj->setPage(1);$obj->setItems(10);// или так$obj->setPage(1)->setItems(10);// выводprint_r($obj->getArray());echo $obj->getTable();// или вообще вот такecho $obj->setPage(1)->setItems(10)->getTable();// а с php 5.4echo (new pageMan())->setPage(1)->setItems(10)->getTable();
#45. tipsun Off (19)
Moderator
2011.12.12 20:08
Ойбле smile
А мануал для чего? smile
- - - -
Ладно, переделаю.
Так еще надо будет следить ввел ли вообще пользователь параметр или нет. sad
- - - -
Код:
span style="color: #0000BB"><?phpecho $obj->setPage(1)->setItems(10)->getTable();//это вроде не проблема.//надо в методе:return $this;?>
Отредактировано tipsun (2011.12.12 20:08)
#46. tipsun Off (19)
Moderator
2011.12.12 21:09
Осталось теперь отслеживать ввод данных.

Код:
span style="color: #0000BB"><?php//BEGIN 'New code' public function setMethod($method) { if (method_exists(__CLASS__, '_method' . $method)) { $this->_method = '_method' . $method; } else { trigger_error('Nonexistent method', E_USER_ERROR); } return $this; } public function setCount($count) { if (is_numeric($count) and 0 < $count) { $this->_count = (int)$count; } else { trigger_error('Value must be integer', E_USER_ERROR); } return $this; } public function setPage($page) { if (is_numeric($page) and 0 < $page) { $this->_tmpPage = (int)$page; } return $this; } public function setItems($items) { if (is_numeric($items)) { if (0 < $items) $this->_items = (int)$items; else $this->_items = $this->_count; } else { $this->_items = self::$_items; } return $this; } //END 'New code'?>
Отредактировано tipsun (2011.12.12 21:09)
#47. Gemor
Гость
2011.12.12 21:09
вынеси свои параметры для setMethod в константы класса хотябы. а вообще я не вижу в setMethod вообще необходимости.
и проверять не надо, используй дефолтовые значения.
#48. tipsun Off (19)
Moderator
2011.12.12 21:09
А, типа как ты показал getArray()/getTable().
Но там тогда надо будет массивом возвращать.
- - - -
Т.к. у меня там getStart точка отсчета.
Знач если getStop не будет, то просто все в одном вернуть и все.
Отредактировано tipsun (2011.12.12 22:10)
#49. Gemorroj Off (107)
Administrator
2011.12.12 22:10
вот в зависимости от get* возвращай как просят.
#50. tipsun Off (19)
Moderator
2011.12.12 22:10
И так и так короче...
Страниц: 13 4 5 6 716 Все
Главная
WEB
PunBB Mod v0.6.2
0.017 s