Pagination Class в CodeIgniter

  • Содержание

Стандартный класс Pagination в CodeIgniter генерирует ссылки вида http://site.com/news/n, где n рассчитывается как [номер страницы] * [количество записей на странице]. Это удобно, так как выборка начинается с записи под номером n. Но я привык передавать в url номер страницы, а не номер записи, поэтому решил изменить библиотеку. И еще одно небольшое изменение. Если Вы зададите опцию $config['url_suffix'], то получите ссылку вроде http://site.com/news.html/5. В результате -  ошибка 404. Внося небольшие поправки в класс, решаем эту проблему.

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class MY_Pagination extends CI_Pagination {

	var $url_suffix			= ''; 

	//——————————————————————————————————
	
	/**
	 * Generate the pagination links
	 *
	 * @access	public
	 * @return	string
	 */	
	function create_links()
	{
		// If our item count or per-page total is zero there is no need to continue.
		if ($this->total_rows == 0 OR $this->per_page == 0)
		{
			return '';
		}

		// Calculate the total number of pages
		$num_pages = ceil($this->total_rows / $this->per_page);

		// Is there only one page? Hm… nothing more to do here then.
		if ($num_pages == 1)
		{
			return '';
		}

		// Determine the current page number.		
		$CI =& get_instance();
		
		$this->url_suffix = $CI->config->item('url_suffix');
		
		if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
		{
			if ($CI->input->get($this->query_string_segment) != 0)
			{
				$this->cur_page = $CI->input->get($this->query_string_segment);
				
				// Prep the current page - no funny business!
				$this->cur_page = (int) $this->cur_page;
			}
		}
		else
		{
			if ($CI->uri->segment($this->uri_segment) != 0)
			{
				$this->cur_page = $CI->uri->segment($this->uri_segment);
				
				// Prep the current page - no funny business!
				$this->cur_page = (int) $this->cur_page;
			}
			$this->base_url = $this->remove_url_suffix($this->base_url, $this->url_suffix);
		}
						
		$this->num_links = (int)$this->num_links;
		
		if ($this->num_links < 1)
		{
			show_error('Your number of links must be a positive number.');
		}
				
		if ( ! is_numeric($this->cur_page))
		{
			$this->cur_page = 0;
		}
		
		if ($this->cur_page < 1)
		{
			$this->cur_page = 1;
		}
		
		// Is the page number beyond the result range?
		// If so we show the last page
		if ($this->cur_page > $num_pages)
		{
			$this->cur_page = $num_pages;
		}
		
		$uri_page_number = $this->cur_page;

		$this->cur_page = floor($this->cur_page);
		

		// Calculate the start and end numbers. These determine
		// which number to start and end the digit links with
		$start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
		$end = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;

		// Is pagination being used over GET or POST? If get, add a per_page query
		// string. If post, add a trailing slash to the base URL if needed
		if ($CI->config->item('enable_query_strings') === TRUE OR $this->page_query_string === TRUE)
		{
			$this->base_url = rtrim($this->base_url).'&'.$this->query_string_segment.'=';
		}
		else
		{
			$this->base_url = rtrim($this->base_url, '/') .'/';
		}

		// And here we go…
		$output = '';

		// Render the "First" link
		if  ($this->cur_page > $this->num_links)
		{
			$output .= $this->first_tag_open.'<a href="'.$this->base_url.'1'.$this->url_suffix.'">'.$this->first_link.'</a>'.$this->first_tag_close;
		}
		
		// Render the "previous" link
		if  ($this->cur_page > 1)
		{
			$i = $this->cur_page - 1;
			if ($i == 0) $i = '';
			$output .= $this->prev_tag_open.'<a href="'.$this->base_url.$i.$this->url_suffix.'">'.$this->prev_link.'</a>'.$this->prev_tag_close;
		}
		
		
		// Write the digit links
		for ($loop = $start -1; $loop <= $end; $loop++)
		{
			$i = $loop;
					
			if ($i > 0)
			{
				if ($this->cur_page == $loop)
				{
					$output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
				}
				else
				{
					$n = ($i == 0) ? '' : $i;
					$output .= $this->num_tag_open.'<a href="'.$this->base_url.$n.$this->url_suffix.'">'.$loop.'</a>'.$this->num_tag_close;
				}
			}
		}

		// Render the "next" link
		if ($this->cur_page < $num_pages)
		{
			$output .= $this->next_tag_open.'<a href="'.$this->base_url.($this->cur_page + 1).$this->url_suffix.'">'.$this->next_link.'</a>'.$this->next_tag_close;
		}
		
		// Render the "Last" link
		if (($this->cur_page + $this->num_links) < $num_pages)
		{
			$i = $num_pages;
			$output .= $this->last_tag_open.'<a href="'.$this->base_url.$i.$this->url_suffix.'">'.$this->last_link.'</a>'.$this->last_tag_close;
		}
		
		// Kill double slashes. Note: Sometimes we can end up with a double slash
		// in the penultimate link so we'll kill all double slashes.
		$output = preg_replace("#([^:])//+#", "\\1/", $output);

		// Add the wrapper HTML if exists
		$output = $this->full_tag_open.$output.$this->full_tag_close;
		
		return $output;		
	}
	
	function remove_url_suffix($base_url = '', $url_suffix = '')	// remove suffix
	{
		if  ($url_suffix != "")
		{
			return preg_replace("|".preg_quote($url_suffix)."$|", "", $base_url);
		}
		return $base_url;
	}
	
}
// END Pagination Class

Запишем ограничение выборки.

if ($page < 1) $page = 1;
$this->db->limit($on_page, ($page - 1) * $on_page);

Скачать исходник

Понравилась статья? Подпишись на RSS.

Советую почитать:

Авторизация

Теги: codeigniter pagination, pagination codeigniter

Slidemenu и Mootools Создание тени средствами JavaScript

Комментарии

  • Юрий написал 29 августа 2009 года

    Не могли бы вы показать небольшой пример с контроллером и моделью?

    Ответить
  • Александр написал 04 сентября 2009 года

    Пример

    Ответить
  • rene написал 17 июля 2010 года

    thanks for this, it took me some time to figure out the russian hahaha

    Ответить
  • sauron918 написал 07 июля 2011 года

    Здравствуйте, нет реализации для CI 2.0?
    Был бы очень признателен

    Ответить
  • Александр написал 08 июля 2011 года

    Здравствуйте, к сожалению, нет

    Ответить
  • alisherdavronov написал 21 октября 2011 года

    привет!
    было непонятно, теперь ок, спасибо (саше).

    для CI 2 заменил

    parent::CI_Pagination($params);

    на

    parent::__construct($params);

    и все работает помоему

    Ответить