PHP . SU
Программирование на PHP, MySQL и другие веб-технологии
Описание: Pagination with jQuery, MySQL and PHP как реализовать на самописном mvc
Поиск в теме | Версия для печати
medensev
Отправлено: 24 Июня, 2013 - 07:07:50
Новичок
Покинул форум
Сообщений всего: 17
Дата рег-ции: Февр. 2012
Откуда: Орел
Помог: 0 раз(а)
Ребят я же попросил и ссылки указал что конкретно мне нужно! А примеров много в глобальной сети). И не нужно рекламировать свою cms). Без обид)
Есть файлы model_news.php view_news.php controller_news.php ниже прикреплю файлы чтобы скачать и посмотреть как выглядит структура mvc
А Pagination можно выбрать один из двух -
1. Этот
http://ratemir[dot]ru/texnologii-jqu[dot][dot].php-i-mysql[dot]html
2. Или этот
http://www[dot]9lessons[dot]info/2009/09[dot][dot][dot]sql-and-php[dot]html
Нужно встроить Pagination по структуре mvc - model_news.php view_news.php controller_news.php или же как библиотеку, только как это сделать я не знаю) поэтому прошу помощи.
Просьба писать здесь ссылки исключительно на готовый архив по теме, даже будет лучше если напишите подробно код как встроить или реализовать "Pagination" в mvc который указан именно в моей теме а не возможные примеры которые можно найти в сети...
Спасибо.
DeepVarvar
Отправлено: 24 Июня, 2013 - 07:23:23
Активный участник
Покинул форум
Сообщений всего: 10377
Дата рег-ции: Дек. 2008
Откуда: Альфа Центавра
Помог: 353 раз(а)
medensev пишет: не нужно рекламировать свою cms
Я вообще не это имел виду. Я сказал бери и пользуй - там юзать как дважды-два, кода как кот наплакал. А решение стоящее. И денег я за то не спрашиваю. Тебе лень вытащить куски кода?
medensev пишет: Просьба писать здесь ссылки исключительно на готовый архив по теме, даже будет лучше если напишите подробно код как встроить или реализовать "Pagination" в mvc
С таким подходом тебе не в эту ветку форума.
И да - МВЦ это не единственный путь, и уж тем более не всегда лучший.
medensev
Отправлено: 24 Июня, 2013 - 07:44:49
Новичок
Покинул форум
Сообщений всего: 17
Дата рег-ции: Февр. 2012
Откуда: Орел
Помог: 0 раз(а)
DeepVarvar vs medensev ))
Если можешь объясни как
DeepVarvar пишет:
там юзать как дважды-два
DeepVarvar
Отправлено: 24 Июня, 2013 - 07:54:51
Активный участник
Покинул форум
Сообщений всего: 10377
Дата рег-ции: Дек. 2008
Откуда: Альфа Центавра
Помог: 353 раз(а)
medensev пишет: Если можешь объясни как
Не понятно, если ты манипулируешь понятиями паттерна МВЦ, который является производным "материалом" понятий ООП, то что тебе тогда надо объяснять?
Во первых на странице, которую я дал ранее, уже есть пример использования.
Во вторых
вот еще .
(Добавление)
Сорцы дать?
Вот:
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
<?PHP
/**
* pagination class
*/
class paginator {
/**
* empty default result
*/
private static
$empty = array (
"number_of_items" => 0 ,
"number_of_pages" => 1 ,
"current_page" => 1 ,
array ( "number" => 1 , "current" => true ) )
) ;
private
/**
* source query of pages without limits
*/
$sourceQuery = null ,
/**
* source query of count items
*/
$countQuery = null ,
/**
* number of items per page
*/
$itemsPerPage = 1 ,
/**
* slice size by pages
*/
$sliceSizeByPages = 20 ,
/**
* number of current page
*/
$currentPage = 1 ,
/**
* output result
*/
$result = null ;
/**
* return default empty result
*/
public static function getEmptyDefault( ) {
return self :: $empty ;
}
/**
* create pagination object example from source query without limits
*/
public function __construct( $sourceQuery ) {
$this -> sourceQuery = $sourceQuery ;
$this -> countQuery = $sourceQuery ;
$this -> result = self :: $empty ;
return $this ;
}
/**
* set current desired page number
*/
public function setCurrentPage( $number ) {
if ( ! utils:: isNumber ( $number ) ) {
throw new systemErrorException( "Pagination error" , "Current page is not number" ) ;
}
if ( $number == 0) {
throw new systemErrorException( "Pagination error" , "Current page can't be zero" ) ;
}
$this -> currentPage = $number ;
return $this ;
}
/**
* set number of items per page
*/
public function setItemsPerPage( $number ) {
if ( ! utils:: isNumber ( $number ) ) {
throw new systemErrorException( "Pagination error" , "Items per page is not number" ) ;
}
if ( $number == 0) {
throw new systemErrorException( "Pagination error" , "Items per page can't be zero" ) ;
}
$this -> itemsPerPage = $number ;
return $this ;
}
/**
* set slice size by pages number
*/
public function setSliceSizeByPages( $number ) {
if ( ! utils:: isNumber ( $number ) ) {
throw new systemErrorException( "Pagination error" , "Slice size by pages is not number" ) ;
}
if ( $number == 0) {
throw new systemErrorException( "Pagination error" , "Slice size by pages can't be zero" ) ;
}
$this -> sliceSizeByPages = $number ;
return $this ;
}
/**
* get result
*/
public function getResult( ) {
$this -> getNumberOfAllItems ( ) ;
$this -> getNumberOfAllPages ( ) ;
$availableNumber = $this -> result [ 'number_of_pages' ] > 0
? $this -> result [ 'number_of_pages' ] : 1 ;
if ( $this -> currentPage > $availableNumber ) {
throw new systemErrorException( "Pagination error" , "Current page is more maximum page number" ) ;
}
$this -> getPages ( ) ;
$this -> getItems ( ) ;
return $this -> result ;
}
/**
* set custom count query
*/
public function setCountQuery( $query ) {
$this -> countQuery = $query ;
}
/**
* get number of all items
*/
private function getNumberOfAllItems( ) {
$countQuery = preg_replace ( "/^(\s*SELECT\s+)(.+)(\s+FROM)/si" , "$1 COUNT(1) cnt $3 " , $this -> countQuery , 1
) ; $this -> result [ 'number_of_items' ] = db:: cachedNormalizeQuery ( $countQuery ) ;
}
/**
* get number of all pages
*/
private function getNumberOfAllPages( ) {
$this -> result [ 'number_of_pages' ] = ceil ( $this -> result [ 'number_of_items' ] / $this -> itemsPerPage ) ; }
/**
* get pages array
*/
private function getPages( ) {
if ( $this -> sliceSizeByPages % 2 != 0) {
$this -> sliceSizeByPages += 1 ;
}
$half = $this -> sliceSizeByPages / 2 ;
$rangeStart = $this -> currentPage - $half ;
$rangeStop = $this -> currentPage + $half ;
$this -> result [ 'pages' ] = array ( ) ; $this -> result [ 'current_page' ] = $this -> currentPage ;
$pagesRange = range ( $rangeStart , $rangeStop ) ;
foreach ( $pagesRange as $item ) {
if ( $item > 0 and $item <= $this -> result [ 'number_of_pages' ] ) {
$page = array ( "number" => $item , "current" => ( $item == $this -> currentPage ) ) ;
}
}
}
/**
* get items for current slice
*/
private function getItems( ) {
$offset = ( $this -> currentPage - 1) * $this -> itemsPerPage ;
$this -> result [ 'items' ] = db:: query (
"{$this->sourceQuery} LIMIT {$offset} , {$this->itemsPerPage} "
) ;
}
}
Тут нужно всего-лишь заменить обращения к объекту базы данных, валидацию (проверки типа на is_int) и обработку исключений.
medensev
Отправлено: 24 Июня, 2013 - 08:38:35
Новичок
Покинул форум
Сообщений всего: 17
Дата рег-ции: Февр. 2012
Откуда: Орел
Помог: 0 раз(а)
Имел ввиду объяснить на примере в моем случаи
вот контроллер controller_news.php (пример)
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
<?PHP
class Controller_News extends Controller
{
function __construct( )
{
$this -> model = new Model_News( ) ;
$this -> view = new View( ) ;
}
function action_index( )
{
$data = $this -> model -> get_data ( ) ;
$this -> view -> generate ( 'view_news.php' , 'template_view.php' , $data ) ;
}
}
Далее модель Model_news.php (пример)
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
<?PHP
class Model_News extends DBase
{
public function get_data( ) {
$stmt = $this -> mysqli -> prepare ( 'SELECT * FROM services ' ) or
die ( "Problem preparing query" ) ; $stmt -> execute ( ) ;
$meta = $stmt -> result_metadata ( ) ;
while ( $field = $meta -> fetch_field ( ) ) {
$parameters [ ] = & $row [ $field -> name ] ;
}
while ( $stmt -> fetch ( ) ) {
foreach ( $row as $key => $val ) {
$x [ $key ] = $val ;
}
$results [ ] = $x ;
}
return $results ;
}
}
Вид View_news.php
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
<?PHP
foreach ( $data as $row )
{
echo '<h2>' . $row [ 'title' ] . '</h2><tr><td></td><td>' . $row [ 'text' ] . '</td><td>' . $row [ 'date' ] . '<br />' . $row [ 'time' ] . '<br />' . $row [ 'author' ] . '</td></tr>' ;
}
?>
DeepVarvar пожалуйста измени эти файлы под Pagination что бы я вставил в ту mvc и начал разбираться что куда и почему, мне так легче понять будет.
Спасибо за помощь!
DeepVarvar
Отправлено: 25 Июня, 2013 - 18:23:40
Активный участник
Покинул форум
Сообщений всего: 10377
Дата рег-ции: Дек. 2008
Откуда: Альфа Центавра
Помог: 353 раз(а)
Кантралёр:
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
class Controller_News extends Controller
{
function __construct( )
{
// модель тут в одно место не впилась
$this -> view = new View( ) ;
}
function action_index( )
{
// почему запрос прямо в контроллере?
// потому, что так надо, и потому что модель.. кхм
// модель не должна содержать в себе более одного результата
// так, если нужно несколько моделей
// этим занимается совсем другой паттерн
// не буду засирать тебе мозг лишней инфой
// у тебя тут тока МВЦ, так пусть оно и остается
// итак - "собираем" запрос прямо в контроллере
$paginator = new paginator( "SELECT * FROM services" ) ;
$data = $paginator -> setCurrentPage ( ( int) $_GET [ 'page' ] )
-> setItemsPerPage ( 20)
-> setSliceSizeByPages ( 20)
-> getResult ( ) ;
$this -> view -> generate ( 'view_news.php' , 'template_view.php' , $data ) ;
}
}
Пагинатор перепиленый под тебя, делается через одно место, ибо не зачем юзать учебный пример с хабра в действующем проекте. Я вообще не гарантирую что оно заработает, т.к. пишу на коленке без проверок, а ты даже пальцем не шевелишь - только в личку отписал, мол, не забудь. Так вот с ошибками сам разберешься. Я вообще не понимаю что там в DBase лежит, если его модель наследует у тебя. Ладно, едем вперед:
Спойлер (Отобразить ) PHP:
скопировать код в буфер обмена
<?PHP
/**
* pagination class
*/
class paginator extends DBase {
/**
* empty default result
*/
private static
$empty = array (
"number_of_items" => 0 ,
"number_of_pages" => 1 ,
"current_page" => 1 ,
array ( "number" => 1 , "current" => true ) )
) ;
private
/**
* source query of pages without limits
*/
$sourceQuery = null ,
/**
* source query of count items
*/
$countQuery = null ,
/**
* number of items per page
*/
$itemsPerPage = 1 ,
/**
* slice size by pages
*/
$sliceSizeByPages = 20 ,
/**
* number of current page
*/
$currentPage = 1 ,
/**
* output result
*/
$result = null ;
/**
* return default empty result
*/
public static function getEmptyDefault( ) {
return self :: $empty ;
}
/**
* create pagination object example from source query without limits
*/
public function __construct( $sourceQuery ) {
$this -> sourceQuery = $sourceQuery ;
$this -> countQuery = $sourceQuery ;
$this -> result = self :: $empty ;
return $this ;
}
/**
* set current desired page number
*/
public function setCurrentPage( $number ) {
throw new Exception( "Pagination error: current page is not number" ) ;
}
if ( $number == 0) {
throw new Exception( "Pagination error: current page can't be zero" ) ;
}
$this -> currentPage = $number ;
return $this ;
}
/**
* set number of items per page
*/
public function setItemsPerPage( $number ) {
throw new Exception( "Pagination error: items per page is not number" ) ;
}
if ( $number == 0) {
throw new Exception( "Pagination error: items per page can't be zero" ) ;
}
$this -> itemsPerPage = $number ;
return $this ;
}
/**
* set slice size by pages number
*/
public function setSliceSizeByPages( $number ) {
throw new Exception( "Pagination error: slice size by pages is not number" ) ;
}
if ( $number == 0) {
throw new Exception( "Pagination error: slice size by pages can't be zero" ) ;
}
$this -> sliceSizeByPages = $number ;
return $this ;
}
/**
* get result
*/
public function getResult( ) {
$this -> getNumberOfAllItems ( ) ;
$this -> getNumberOfAllPages ( ) ;
$availableNumber = $this -> result [ 'number_of_pages' ] > 0
? $this -> result [ 'number_of_pages' ] : 1 ;
if ( $this -> currentPage > $availableNumber ) {
$this -> currentPage = $availableNumber ;
}
$this -> getPages ( ) ;
$this -> getItems ( ) ;
return $this -> result ;
}
/**
* set custom count query
*/
public function setCountQuery( $query ) {
$this -> countQuery = $query ;
}
/**
* get number of all items
*/
private function getNumberOfAllItems( ) {
"/^(\s*SELECT\s+)(.+)(\s+FROM)/si" ,
"$1 COUNT(1) cnt $3 " ,
$this -> countQuery ,
1
) ;
$this -> result [ 'number_of_items' ] = $this -> innerQuery ( $countQuery ) ;
}
/**
* get number of all pages
*/
private function getNumberOfAllPages( ) {
$this -> result [ 'number_of_pages' ]
= ceil ( $this -> result [ 'number_of_items' ] / $this -> itemsPerPage ) ; }
/**
* get pages array
*/
private function getPages( ) {
if ( $this -> sliceSizeByPages % 2 != 0) {
$this -> sliceSizeByPages += 1 ;
}
$half = $this -> sliceSizeByPages / 2 ;
$rangeStart = $this -> currentPage - $half ;
$rangeStop = $this -> currentPage + $half ;
$this -> result [ 'pages' ] = array ( ) ; $this -> result [ 'current_page' ] = $this -> currentPage ;
$pagesRange = range ( $rangeStart , $rangeStop ) ;
foreach ( $pagesRange as $item ) {
if ( $item > 0 and $item <= $this -> result [ 'number_of_pages' ] ) {
$page = array ( "number" => $item , "current" => ( $item == $this -> currentPage ) ) ;
}
}
}
/**
* get items for current slice
*/
private function getItems( ) {
$offset = ( $this -> currentPage - 1) * $this -> itemsPerPage ;
$this -> result [ 'items' ] = $this -> innerQuery (
"{$this->sourceQuery} LIMIT {$offset} , {$this->itemsPerPage} "
) ;
}
private function innerQuery( $query ) {
$stmt = $this -> mysqli -> prepare ( $query ) or
die ( "Problem preparing query" ) ; $stmt -> execute ( ) ;
$meta = $stmt -> result_metadata ( ) ;
while ( $field = $meta -> fetch_field ( ) ) {
$parameters [ ] = & $row [ $field -> name ] ;
}
while ( $stmt -> fetch ( ) ) {
foreach ( $row as $key => $val ) {
$x [ $key ] = $val ;
}
$results [ ] = $x ;
}
return $results ;
}
}
Вьюха:
Спойлер (Отобразить ) CODE (
htmlphp ):
скопировать код в буфер обмена
< h1> Это твои "новости":</ h1>
<? php foreach ( $data [ 'items' ] as $row ) { ?>
< h2> <?= $row [ 'title' ] ?> </ h2>
< div>
<?= $row [ 'text' ] ?> <?= $row [ 'date' ] ?> <?= $row [ 'time' ] ?> <?= $row [ 'author' ] ?>
</ div>
<? php } ?>
Это страницы:
< div>
<? php foreach ( $data [ 'pages' ] as $page ) { ?>
< a href= "/news?page=<?=$page ['number']?> "><?= $page [ 'number' ] ?> </ a>
<? php } ?>
</ div>
Вообще, если ставить диагноз - тебе рановато еще ООП.
Однако стремление изучать должно принести свои плоды.
Поэтому, если тут возникнут ошибки - разбери их сам.
medensev
Отправлено: 25 Июня, 2013 - 20:08:05
Новичок
Покинул форум
Сообщений всего: 17
Дата рег-ции: Февр. 2012
Откуда: Орел
Помог: 0 раз(а)
DeepVarvar Спасибо! буду разбираться.
(Добавление)
DeepVarvar не работает(
Цитата: Fatal error: Uncaught exception 'Exception' with message 'Pagination error: current page can't be zero' in C:\OpenServer\domains\localhost\fm.ru\application\core\paginator.php:112 Stack trace: #0 C:\OpenServer\domains\localhost\fm.ru\application\controllers\controller_pagenews.php(26): Paginator->setCurrentPage(0) #1 C:\OpenServer\domains\localhost\fm.ru\application\core\route.php(74): Controller_PageNews->action_index() #2 C:\OpenServer\domains\localhost\fm.ru\application\bootstrap.php(26): Route::start() #3 C:\OpenServer\domains\localhost\fm.ru\index.php(4): require_once('C:\OpenServer\d...') #4 {main} thrown in C:\OpenServer\domains\localhost\fm.ru\application\core\paginator.php on line 112
Поиск в теме | Версия для печати
Страниц (1): [1]
Сейчас эту тему просматривают: 0 (гостей: 0, зарегистрированных: 0)
« Программирование на PHP »
Все гости форума могут просматривать этот раздел. Только зарегистрированные пользователи могут создавать новые темы в этом разделе. Только зарегистрированные пользователи могут отвечать на сообщения в этом разделе.
Powered by ExBB FM 1.0 RC1. InvisionExBB