CI 코드

제목 MY_Pagination 과거로의 회귀...
글쓴이 darkninja 작성시각 2022/12/09 20:01:26
댓글 : 0 추천 : 0 스크랩 : 0 조회수 : 31732   RSS

ci4의 페이지네이션은 숫자링크들의 갯수가 가변적이라서

소스수정을 시도했는데 당장 해결할수가 없어서 (공부하기 싫어서..)

ci3의 페이지네이션 소스를 ci4에 적용 시키는 꼼수를

이해 불가능한 소스는 삭제하고 변수들의 이름을 이해하기 쉽게 바꾸었는데 이건 저만의 기준이고

그냥 학습용입니다.

 

Controllers/board.php

<?php namespace App\Controllers;

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

use App\Libraries\MY_Pagination; //이 줄을 추가

class Board extends BaseController {

.
.
    // show a list of board
    public function index($board_table=BOARD, $page_index=1, $order='modify_date', $asc='desc') 
    {
		$per_page = $this->per_page;
    	$total_rows = 0;
    	$boards = $this->board_model->paginated_reply($board_table, $page_index, $per_page, $total_rows, $order, $asc);
        $redirect_url = $this->board_controller.'/index/'.$board_table;
        $base_url = ROOT_PATH.'/'.$redirect_url;

    	//$template_name = 'default_full';
    	//$uri_segment = 6;
    	//$group = 'default';
    	//$pager = service('pager');
    	//$pager->setPath($base_url, $group); // Additionally you could define path for every group.
    	//$pageLinks = $pager->makeLinks($page_index, $per_page, $total_rows, $template_name, $uri_segment, $group);    

        $MyPager = new MY_Pagination();
		$page_config = array();
		$page_config['base_url'] = $base_url;
		$page_config['per_page'] = $per_page;
		$page_config['total_rows'] = $total_rows;
		$page_config['uri_segment'] = 4;
		$MyPager->initialize($page_config);
        $pageLinks = $MyPager->create_links();

    	$t = intval(($total_rows-1) / $per_page) + 1;
    	if ($page_index > $t) {
      	    $this->response->redirect(site_url($redirect_url.'/'.$t));
	    }

    	$data = Array(
      		'head_data' => Array(
        		'title' => 'Board list',
      		),
    	  	'view_data' => Array(
	        	'boards' => $boards,
		        'pageLinks' => $pageLinks,
    		    'cut_contents' => $this->cut_contents,
        		'board_table' => $board_table,
	        	'comment_table' => $board_table.COMMENT,
    		    'page_index' => $page_index,
		        'db' => $this->db,
    		    'board_table' => $board_table,
        		'board_model' => $this->board_model,
      		),
	    );

    	$this->render_page('index', $data);
  	}

    // render_page
    private function render_page($view, $data) 
	{
        $view = $this->board_controller .'/'. $this->board_skin .'/'. $view;
        $data = array_replace_recursive($this->data, $data);

        echo view('main_head_board', $data['head_data']);
        echo view($view, $data['view_data']);
        echo view('main_tail_board', $data['tail_data']);
    }

css/pagination.css

.pagination {
  display: inline-block;
  padding: 0;
  margin: 0;
  border-radius: 4px;
}
.pagination > li {
  display: inline;
}
.pagination > li > a,
.pagination > li > span {
  position: relative;
  float: left;
  padding: 2px 4px 0 4px;
  margin-left: -0px;
  line-height: 1.42857143;
  color: #2fa4e7;
  text-decoration: none;
  background-color: #fff;
  border: 1px solid #ddd;
  font-size: 13px;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
  margin-left: 0;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
  color: #157ab5;
  background-color: #eee;
  border-color: #ddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
  z-index: 2;
  color: #fff;
  cursor: default;
  background-color: #2fa4e7;
  border-color: #2fa4e7;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
  color: #777;
  cursor: not-allowed;
  background-color: #fff;
  border-color: #ddd;
}

Libraries/My_pagination.php

<?php 
namespace App\Libraries; //이 줄을 추가

defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Pagination 
{
    protected $request;
    protected $uri;

	protected $base_url	           = '';
	protected $prefix              = '';
	protected $suffix              = '';

	protected $total_rows          = 0;
	protected $current_page        = 0;
	protected $uri_segment         = 3;

	protected $per_page            = 10;
	protected $num_links_previous  = 5;
	protected $num_links_next      = 5;

	protected $display_pages       = TRUE;
	protected $page_query_string   = FALSE;
	protected $reuse_query_string  = FALSE;
	protected $one_pages_return    = FALSE;

	protected $first_url           = '';
	protected $query_string_segment = 'per_page';
	protected $num_links; //program use, do not set. it mean ($num_links_previous + $num_links_next)

	protected $full_tag_open       = '<nav><ul class="pagination">';
	protected $full_tag_close      = '</ul></nav>';

	protected $first_link          = 'First';
	protected $first_tag_open      = '<li>';
	protected $first_tag_close     = '</li>';

	protected $previous_link       = 'Previous';
	protected $previous_tag_open   = '<li>';
	protected $previous_tag_close  = '</li>';

	protected $previous_page_link      = 'Previous page';
	protected $previous_page_tag_open  = '<li>';
	protected $previous_page_tag_close = '</li>';

	protected $next_page_link      = 'Next page';
	protected $next_page_tag_open  = '<li>';
	protected $next_page_tag_close = '</li>';

	protected $next_link           = 'Next';
	protected $next_tag_open       = '<li>';
	protected $next_tag_close      = '</li>';

	protected $last_link           = 'Last';
	protected $last_tag_open       = '<li>';
	protected $last_tag_close      = '</li>';

	protected $current_tag_open    = '<li class="active">';
	protected $current_tag_close   = '</li>';

	protected $num_tag_open        = '<li>';
	protected $num_tag_close       = '</li>';

	protected $link_info_style     = 'style="background-color:yellow;"'; //first and last link style.

	/**
	 * Constructor
	 */
	public function __construct($params = array())
	{
		if (count($params) > 0)	{
			$this->initialize($params);
		}

		log_message('debug', 'Pagination Class Initialized');
	}

	public function initialize(array $params = array())
	{
		foreach ($params as $key => $val) {
			if (property_exists($this, $key)) {
				$this->$key = $val;
			}
		}

		$this->request = \Config\Services::request();
		$this->uri = $this->request->uri;

		$pager_config = config('Pager');
		if (isset($pager_config->enable_query_strings)) {
			$this->page_query_string = $pager_config->enable_query_strings;
		}
	}

	public function create_links()
	{
		// If our item count or per-page total is zero there is no need to continue.
		// Note: DO NOT change the operator to === here!
		if ($this->total_rows == 0 OR $this->per_page == 0) {
			return '';
		}

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

		// Is there only one page? Hm... nothing more to do here then.
		if ($this->one_pages_return && $num_pages == 1) {
			echo 'Is there only one page? Hm... nothing more to do here then.<br><br>';
			return '';
		}

		// Check the user defined number of links.
		$this->num_links_previous = (int) $this->num_links_previous;
		$this->num_links_next = (int) $this->num_links_next;
		if ($this->num_links_previous < 1 || $this->num_links_next < 1)	{
			echo 'Your number of links must be a positive number.<br><br>';
		    $this->num_links_previous = 5;
		    $this->num_links_next = 5;
		}
		
		$this->num_links = $this->num_links_previous + $this->num_links_next;

		// Keep any existing query string items.
		// Note: Has nothing to do with any other query string option.
		if ($this->reuse_query_string === TRUE)	{
			$get = $this->request->getvar();

			// Unset the controll, method, old-school routing options
			unset($get['c'], $get['m'], $get[$this->query_string_segment]);
		}
		else {
			$get = array();
		}

		// Put together our base and first URLs.
		// Note: DO NOT append to the properties as that would break successive calls
		$base_url = trim($this->base_url);
		$first_url = $this->first_url;

		$query_string = '';
		$query_string_sep = (strpos($base_url, '?') === FALSE) ? '?' : '&';

		// Are we using query strings?
		if ($this->page_query_string === TRUE) {
			// If a custom first_url hasn't been specified, we'll create one from
			// the base_url, but without the page item.
			if ($first_url === '') {
				$first_url = $base_url;

				// If we saved any GET items earlier, make sure they're appended.
				if ( ! empty($get)) {
					$first_url .= $query_string_sep.http_build_query($get);
				}
			}

			// Add the page segment to the end of the query string, where the
			// page number will be appended.
			$base_url .= $query_string_sep.http_build_query(array_merge($get, array($this->query_string_segment => '')));
		}
		else {
			// Standard segment mode.
			// Generate our saved query string to append later after the page number.
			if ( ! empty($get)) {
				$query_string = $query_string_sep.http_build_query($get);
				$this->suffix .= $query_string;
			}

			// Does the base_url have the query string in it?
			// If we're supposed to save it, remove it so we can append it later.
			if ($this->reuse_query_string === TRUE && ($base_query_pos = strpos($base_url, '?')) !== FALSE) {
				$base_url = substr($base_url, 0, $base_query_pos);
			}

			if ($first_url === '') {
				$first_url = $base_url.$query_string;
			}

			$base_url = rtrim($base_url, '/').'/';
		}

		// Determine the current page number.
		$base_page = 1;

		// Are we using query strings?
		if ($this->page_query_string === TRUE) {
			$this->current_page = $this->request->getVar($this->query_string_segment);
		}
		else {
			// Default to the last segment number if one hasn't been defined.
			if ($this->uri_segment === 0) {
				$this->uri_segment = $this->uri->getTotalSegments();
			}

//echo $this->uri->getTotalSegments()."<br>";
//echo $this->uri_segment."<br>";
//exit;

			$this->current_page = $this->uri->getSegment($this->uri_segment);

			// Remove any specified prefix/suffix from the segment.
			if ($this->prefix !== '' OR $this->suffix !== '') {
				$this->current_page = str_replace(array($this->prefix, $this->suffix), '', $this->current_page);
			}
		}

		// If something isn't quite right, back to the default base page.
		if (!ctype_digit($this->current_page)) {
			$this->current_page = $base_page;
		}
		else {
			// Make sure we're using integers for comparisons later.
			$this->current_page = (int) $this->current_page;
		}

		// Is the page number beyond the result range?
		// If so, we show the last page.
		if ($this->current_page > $num_pages) {
			$this->current_page = $num_pages;
		}

		// Calculate the start and end numbers.
		// These determine which number to start and end the digit links with.
		if ($this->current_page > $this->num_links_previous) {
			$start = $this->current_page - $this->num_links_previous;
		} else {	
			$start = 1;
		}	
		if (($this->current_page + $this->num_links_next) < $num_pages) {
			$end = $this->current_page + $this->num_links_next;
			if ($num_pages <= ($this->num_links + 1)) { // num_pages < num_links + 1
				$end = $num_pages;
			}	
		} else {	
			$end = $num_pages;
		}	

		//Re Calculate the start and end numbers. 
		//For fixed num links!
		$tend = $start + $this->num_links; // start + num_links != current_page + num_links_next;
		if ($tend > $num_pages) { 
			$start = $num_pages - $this->num_links;
			if ($start < 1) {
				$start = 1;
			}
		}	
		if ($end < $tend && $tend <= $num_pages) {
			$end = $tend;
		}	
		if ($start > $end) {
			$start = $end;
		}
		
		// And here we go...
		$output = '';
		$link_page = 0;

		// Render the "First" link.
		if ($this->first_link !== FALSE) {
			$link_page = $base_page;
			if ($this->current_page > ($this->num_links_previous + 1)) {
				$url = $base_url.$this->prefix.$link_page.$this->suffix;
				$output .= $this->first_tag_open.'<a href="'.$url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
			}
			else {
				$url = $base_url.$this->prefix.$link_page.$this->suffix;
				$output .= $this->first_tag_open.'<a '.$this->link_info_style.' href="'.$url.'">'.$this->first_link.'</a>'.$this->first_tag_close;
			}	
		}

		// Render the "Previous" link.
		if ($this->previous_link !== FALSE) {
			if (($this->current_page - $this->num_links_previous) > 1) {
				$link_page = $this->current_page - $this->num_links_previous;
			}
			else {
				$link_page = 1;
			}
			$url = $base_url.$this->prefix.$link_page.$this->suffix;
			$output .= $this->previous_tag_open.'<a href="'.$url.'">'.$this->previous_link.'</a>'.$this->previous_tag_close;
		}

		// Render the "Previous page" link.
		if ($this->previous_page_link !== FALSE) {
			if ($this->current_page > 1) {
				$link_page = $this->current_page - 1;
			}
			else {
				$link_page = 1;
			}
			$url = $base_url.$this->prefix.$link_page.$this->suffix;
			$output .= $this->previous_page_tag_open.'<a href="'.$url.'">'.$this->previous_page_link.'</a>'.$this->previous_page_tag_close;
		}

		// Render the pages
		if ($this->display_pages !== FALSE) {
			// Write the digit links
			for ($loop = $start; $loop <= $end; $loop++) {
				$link_page = $loop;
				$url = $base_url.$this->prefix.$link_page.$this->suffix;
				if ($link_page >= $base_page) {
					if ($this->current_page === $link_page) {
						$output .= $this->current_tag_open.'<a href="'.$url.'">'.$link_page.'</a>'.$this->current_tag_close;
					}
					else {
						$output .= $this->num_tag_open.'<a href="'.$url.'">'.$link_page.'</a>'.$this->num_tag_close;
					}
				}
			}
		}

		// Render the "next page" link
		if ($this->next_page_link !== FALSE) {
			if ($this->current_page < $num_pages) {
				$link_page = $this->current_page + 1;
			}
			else {
				$link_page = $num_pages;
			}
			$url = $base_url.$this->prefix.$link_page.$this->suffix;
			$output .= $this->next_page_tag_open.'<a href="'.$url.'">'.$this->next_page_link.'</a>'.$this->next_page_tag_close;
		}

		// Render the "next" link
		if ($this->next_link !== FALSE) {
			if (($this->current_page + $this->num_links_next) < $num_pages) {
				$link_page = $this->current_page + $this->num_links_next;
			}
			else {
				$link_page = $num_pages;
			}
			$url = $base_url.$this->prefix.$link_page.$this->suffix;
			$output .= $this->next_tag_open.'<a href="'.$url.'">'.$this->next_link.'</a>'.$this->next_tag_close;
		}

		// Render the "Last" link
	    if ($this->last_link !== FALSE) {
			$link_page = $num_pages;
			$url = $base_url.$this->prefix.$link_page.$this->suffix;
			if (($this->current_page + $this->num_links_next) < $num_pages) {
				$output .= $this->last_tag_open.'<a href="'.$url.'">'.$this->last_link.'</a>'.$this->last_tag_close;
			}
			else {
				$output .= $this->last_tag_open.'<a '.$this->link_info_style.' href="'.$url.'">'.$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);

		//$output .= " total_rows:".$this->total_rows;
		//$output .= " num_pages:".$num_pages;
		//$output .= " start:".$start;
		//$output .= " current_page:".$this->current_page;
		//$output .= " end:".$end;
		//$output .= " tend:".$tend;
		//$output .= " num_links_previous:".$this->num_links_previous;
		//$output .= " num_links_next:".$this->num_links_next;
		//$output .= " per_page:".$this->per_page;
		
		// Add the wrapper HTML if exists
		return $this->full_tag_open.$output.$this->full_tag_close;
	}

}

?>

view/index.php

<?php if ($boards): ?>

	<?php if ($session->getFlashdata('message')){echo '<p class="success">'.$session->getFlashdata('message').'</p>';} ?>

	<span class="pull-right">
		<span class="pagination">
		    <?php if ($isloggedIn): ?>
			<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/create/'.$board_table; ?>">글쓰기</a></li>
 	        <?php endif; ?>
			<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/indexlist/'.$board_table.'/'.$page_index; ?>">목록</a></li>
		</span>	
	</span>
	<?php echo $pageLinks; ?>
	<div class="clearfix"></div>
	
	<?php foreach($boards as $o):?>
    <?php 
		if ($o->depth==0) {
			echo '<div class="board-outer">';
		}
		else if ($o->depth<10) {
			echo '<div style="margin:5px 0 5px '.(10*$o->depth).'px">';
		}
		else {
			echo '<div style="margin:5px 0 5px '.(10*10).'px">';
		}
    ?>
      <div class="panel panel-info">
        <div class="panel-heading">
          <span class="pull-right panel-subtitle">
            <?php $phpdate = strtotime($o->modify_date);
                //echo date('Y/m/d H:i:s', $phpdate);
                echo date('Y/m/d H:i', $phpdate);
            ?>
            <?php $phpdate = strtotime($o->reg_date);
                echo date('Y/m/d', $phpdate);
            ?>
            <?php if ($o->user_id == $session->get('user_id')) { ?>
              <?php if ($board_replymode == MULTI_DEPTH) { ?>
                    <a href="<?php echo ROOT_PATH.'/'.$board_controller.'/create_closure/'.$board_table.'/'.$o->board_id.'/'.$o->id.'/'.$o->group.'/'.$o->depth.'/'.$o->order.'/'.$page_index; ?>" >답글쓰기</a>
			  <?php } ?>
              <a href="<?php echo ROOT_PATH.'/'.$board_controller.'/edit/'.$board_table.'/'.$o->id; ?>">수정</a>
              <!--a href="<?php echo ROOT_PATH.'/'.$board_controller.'/edit_table/'.$board_table.'/'.$o->id; ?>">테이블수정</a-->
              <!--a href="<?php echo ROOT_PATH.'/'.$board_controller.'/move_table/'.$board_table.'/'.$o->id.'/'.$seg_index; ?>">머신테이블이동</a-->
              <a href="<?php echo ROOT_PATH.'/'.$board_controller.'/delete/'.$board_table.'/'.$o->id.'/'.true; ?>" onclick="return confirm('<?php echo $o->subject.'\r\n'; ?>삭제 하시겠습니까?')">삭제</a>
            <?php } ?>	
          </span>
          <div class="panel-title">
            <?php 
                if ($o->category_name) {
                    echo "[".$o->category_name."] ";
                }	
                echo '<a href="'.ROOT_PATH.'/'.$board_controller.'/view/'.$board_table.'/'.$o->id.'">'.$o->subject.'</a>';
                if ($o->reply_count) {
                    $query = $db
                        ->table($comment_table)
                        ->select('id')
                        ->where('board_id', $o->id)
                        ->orderby('modify_date', 'desc')
                        ->get(1)
                        ;
                
                    if ($query and $query->getRow() !== 0) {
                        $temp_o = $query->getRow();
                        $reply_href = ROOT_PATH.'/'.$board_controller.'/view/'.$board_table.'/'.$o->id.'#comment-'.$temp_o->id;
                        echo '[<a href='.$reply_href.'>'.$o->reply_count.'</a>]';
                    }	
                }	
            ?>
          </div>
          <div class="clearfix"></div>
        </div>
        <div class="panel-body">
          <?php
            // view 에서 전체를 보여줄때는 htmlspecialchars 함수를 사용하지 않고
            // ckeditor 에 넘겨줄때는 (text area 에 내용을 넣을때)
            // <textarea id="contents" name="contents"><?php echo htmlspecialchars($board->contents); ?></textarea>
            // 반드시 htmlspecialchars 함수를 사용해서 념겨주어야
            // html tag 가 포함된 contents 가 ckeditor 에서 source code 형태로 보여진다.
            $str = htmlspecialchars($o->contents); 
            $str = mb_substr($str, 0, $cut_contents, "UTF-8"); 
            echo $str; 
          ?>	
          <div>
            <?php
                if ($o->tag) {
                    echo "tag : [ ".$o->tag." ]";
                } else {
                    echo "tag : 태그가 없습니다.";
                }
            ?>	
          </div>
          <?php echo 'id: '.$o->id.' board_id: '.$o->board_id.' group: '.$o->group.' depth: '.$o->depth.' order: '.$o->order; ?>
        </div>
      </div>
    </div>
	<?php endforeach; ?>
	
	<span class="pull-right">
		<span class="pagination">
		    <?php if ($isloggedIn): ?>
			<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/create/'.$board_table; ?>">글쓰기</a></li>
 	        <?php endif; ?>
			<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/indexlist/'.$board_table.'/'.$page_index; ?>">목록</a></li>
		</span>	
	</span>
	<?php echo $pageLinks; ?>
	<div class="clearfix"></div>
		
<?php else: ?>
	<span class="pagination">
		<?php if ($isloggedIn): ?>
		<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/create/'.$board_table; ?>">글쓰기</a></li>
 	    <?php endif; ?>
		<li><a href="<?php echo ROOT_PATH.'/'.$board_controller.'/indexlist/'.$board_table.'/'.$page_index; ?>">목록</a></li>
	</span>	
	<h3>No boards yet</h3>
<?php endif; ?>

 

 이전글 CI4.1.2 한글언어팩 배포 (CI v4.1.3에서 ... (13)

댓글

없음