SitePoint Sponsor

User Tag List

Page 2 of 2 FirstFirst 12
Results 26 to 44 of 44
  1. #26
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the last post. It's more clear now.

    But,
    Is
    PHP Code:
    $pagi_obj->limit 
    - all this - , a property of the class Pagination ?

    When we do something like this:
    PHP Code:
    $pagi_obj->page $page
    We are telling that the attribute passed on the method Pagination, called $page, will be referenced by our class property
    PHP Code:
    $pagi_obj->page 
    , that by the way, is also a stdClass property? Is this a correct reading? If not, how can we properly read it?

    I'm sorry, if somehow, you have already reply to this, I'm just not connecting all the dots yet.
    :s


    Regards,
    Márcio
    Last edited by oikram; Jul 30, 2009 at 07:43. Reason: forgot to thanks last post

  2. #27
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    No, limit is a property of the object being returned by calling Pagination::Pagination. That method returns a object(instance) of the stdObject class.

    This explains standard object for you. Think of it like a glorified array.

  3. #28
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot. I will now try to connect the dots, and bring some pagination class code.


  4. #29
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello again,

    Quote Originally Posted by oddz View Post
    PHP Code:
    $p Pagination::Pagination(3000,20,1);
    $p->offset
    In the end the listAnimals call would look like:

    PHP Code:
    $dao->listAnimals($p->limit,$p->offset); 
    Do we need to assign a variable to our static method call ?
    Or, since he returns an object, we can access that object properties without the use of the variable?

    Do we need:
    $p=Pagination::Pagination(etc...)
    and then:
    $p->limit;

    or we can have only:
    Pagination::Pagination(etc...)

    and supposing that he returns an object called $page_obj, we will have:
    $page_obj->limit;


    ?

    Thanks,
    Márcio

  5. #30
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I will try to var_dump. I must get use to it. :-)

  6. #31
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by oikram
    Do we need to assign a variable to our static method call ?
    nope

    Quote Originally Posted by oikram
    since he returns an object, we can access that object properties without the use of the variable?
    yep

    PHP Code:
    echo '<pre>',print_r(Pagination::Pagination(3000,20,1)),'</pre>'

  7. #32
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well... actually, when I have no variable associated to my static method call, I'm unable to see a print_r().
    However, when I have a variable associated to my static method call (let's say $p) and then I call the proprieties like this: $p->limit; I DO get print_r() output.


    Can I learn how can I track this error?

    I'm having the following error:

    Warning: Invalid argument supplied for foreach() in /home/cantinho/www/meu/pt/meu-cantinho/lista_associacao.php on line 156

    I believe I'm getting this error, because my listar method doesn't return the object as it should, however, I have made print_r($records); but I get nothing outputted, so I'm unable to see what's going on. What can I do? :s


    *Here is the class method:*

    PHP Code:
    public function listar($limit$offset
        {
            try

            {
                
    $query_str="SELECT * FROM associacao";

                if (!
    is_null($limit) && !is_null($offset))
                {
                    
    $stmt $this->_dbh->prepare($query_str 'LIMIT :limit, :offset');
                    
    $stmt->bindParam(':limit'$limitPDO::PARAM_INT);
                    
    $stmt->bindParam(':offset'$offsetPDO::PARAM_INT);
                }
                
                else if(!
    is_null($limit)) 
                {
                    
    $stmt $this->_dbh->prepare($query_str 'LIMIT :limit');
                    
    $stmt->bindParam(':limit'$limitPDO::PARAM_INT);
                }
                
                else
                {
                     
                    
    $stmt->execute();    
                    
    $records $stmt->fetchObject();
                    
                    return 
    $records;
                    
                } 
            }
            catch (
    PDOException $ex
            {
                
                echo 
    "Erro: " $ex->getMessage();
            }
            
        } 
    *In my list.php file:*

    PHP Code:
    //I send the params to my listar method:
    $associacao_dao->listar($limit$offset);

    //And finally, the line that throws the warning:
    foreach($records as $record)
    {
        
    $conteudo '
        <tr>
        <td>' 
    $record->nome_associacao '</td>
        <td>' 
    $record->morada_associacao.'</td>
          </tr>'
    ;


    It seems that the listar method doesn't return any object...
    I do print_r($records); but I see nothing.


    1) Can I have your help on figuring out what's going on?
    2) What can we do, to debug something like this for future occurrences?



    Thanks a lot AGAIN,
    Márcio

  8. #33
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Update:


    The class is accepting the params and retrieving them well.

    I have done this:

    PHP Code:
    $stmt->execute();
    var_dump($stmt->execute());
                    
    $stmt->fetchObject();
    var_dump($stmt->fetchObject()); 
    And both are giving FALSE. This means, that I have an error.

    But I don't see what could it be the cause.

    []'s
    Márcio

  9. #34
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The error was related with this:

    $associacao_dao->listar($limit, $offset);

    I wasn't having any variable to grab the return value of listar method.


    Márcio

  10. #35
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Something like this perhaps (untested)

    PHP Code:
    public function listar($limit=null$offset=null) {

            
    $rows = array();
            
    $query_str="SELECT * FROM associacao";
            
            
    /*
            * Set up generic bind arrays and modify SQL
            */ 
            
    if (!is_null($limit) && !is_null($offset)) {
                 
    $bind_params = array(
                     array(
    'name'=>':limit','value'=>$limit,'type'=>PDO::PARAM_INT)
                     ,array(
    'name'=>':offset','value'=>$offset,'type'=>PDO::PARAM_INT)
                 );
                 
    $query_str.= 'LIMIT :limit, :offset'
             
    } else if(!is_null($limit)) {
                 
    $bind_params = array(
                     array(
    'name'=>':limit','value'=>$limit,'type'=>PDO::PARAM_INT)
                 );
                 
    $query_str.= 'LIMIT :limit'
             
    } else {
                 
    $bind_params = array();
             }
            
            
    /*
            * Prepare, bind and execute query
            */
            
    if($stmt $this->_dbh->prepare($query_str)) {
                
                foreach(
    $bind_params as $bind_param) {
                    
    $stmt->bindParam($bind_param['name'],$bind_param['value'],$bind_param['type']);
                }
                
                if(
    $stmt->execute()) {
                    while(
    $row $stmt->fetch(PDO::FETCH_OBJ)) {
                        
    $rows[] = $row;
                    }
                }
            
            }
            
            
    /*
            * If limit of 1 return single object or null
            * Otherwise return array as collection of objects
            */
            
    if($limit==1) {
                return empty(
    $rows)?null:$rows[0];
            } else {
                return 
    $rows;
            }
            


  11. #36
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Wow, with you I DO learn. You have changed the code completly but it's a nice exercice to see if I really understand where things are.

    BUT, well, I will just do like I was doing before, just to see if works, and then, little by little, I will change to a better former and structured code as the one provided.

    In 6 hours, I will try to make this WOW YEAH AMAZING COMPLEX little and flaw tiny pagination :s to work.

    And then, try to put it better.

    Regards,
    Márcio

  12. #37
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here we go:

    The pagination class now looks like this:


    PHP Code:
    <?php

    /*
     * @Data: 06-08-2009
     */

    class Paginacao 
    {
        
        

        
    /* @Faz os cálculos para a paginação.
         * 
         * @scope public static
         * 
         * @param int $pag_actual 
         * 
         * @param int $limit
         * 
         * @param int $pag_actual
         * 
         * @return object
         * 
         */
        

        
        
    public static function getInfo($total_registos$limit$pag_actual)    
        {
            
            
            
    $ultima_pagina ceil($total_registos $limit);
            
            
            if (
    $pag_actual $ultima_pagina)
            {
            
                
    $pag_actual $ultima_pagina;
            }
            
            else if (
    $pag_actual 1)
            {
                
                
    $pag_actual 1;
            }
            
            
            
    $offset = ($pag_actual 1) * $limit;

            
    $pagi_obj = (object)array('ultima_pagina'=>$ultima_pagina'offset'=>$offset'limit'=>$limit'pag_actual'=>$pag_actual);
            
            
            return 
    $pagi_obj;
            
        }
    //fim do getInfo  
        
            
    }//fim da classe

    ?>
    Then I have this on my listAssociacao.php:
    PHP Code:
    <?php
        
        
    require_once("AssociacaoDAO.class.php");
        require_once(
    "Paginacao.class.php");
        
        
        
    /* @total de registos */
        
    $associacao_dao = new AssociacaoDAO();
        
    $total_registos $associacao_dao->contar();
        
        
        
        
    /* @pag_actual */ 
        
    if (filter_has_var(INPUT_GET'pagina') == false
        {
            
    $pag_actual 1;
        }
            else 
        {
            
    $pag_actual = (int)$_GET['pagina'];
        }
        
        
        
    /* @limit */
        
    if (filter_has_var(INPUT_GET'limit') == true
        {
            
    $limit = (int)$_GET['limit'];        
        }
        else
        {
            
    //por omissão:
            
    $limit 3;
        }
        
        
        
        
    /* @Paginacao */
        
    $pagi Paginacao::getInfo($total_registos->total$limit$pag_actual);
                
        
    $offset         $pagi->offset;
        
    $limit             $pagi->limit;
        
    $ultima_pagina  $pagi->ultima_pagina;    
        
    $pag_actual     $pagi->pag_actual;
        
        
        
        
    /* @Com os dados obtidos, constrói o conteúdo e os links de navegação */
        
        /* @conteúdo */
        
    $records=$associacao_dao->listar($offset$limit);
        
        
    $conteudo '';
        
        foreach(
    $records as $record)
        {
                    
            
    $conteudo .= '
                <tr>
                    <td>' 
    $record->nome_associacao '</td>
                    <td>' 
    $record->telefone_associacao .'</td>
                </tr>'

        }
        
        
        
    /* @links_navegacao */
        
        //define a variável:
        
    $links_navegacao='';
        
        
    /*
         * @nome_pagina 
         */
        
    $nome_pagina htmlentities($_SERVER['PHP_SELF']);
                
                
        
    /*
        * @menu: link anterior
        */        
        
    if($pag_actual 1
        {
             
    $links_navegacao '<li><a href="' $nome_pagina '?pagina=' . ($pag_actual 1) . '">Anterior</a></li>';
        }
                
        
        
    /*
        * @menu: numeros
        */
        //define a variável:
        
    $i=null;
                
        for (
    $i$i<=$ultima_pagina$i++)
        {
            if (
    $i == $pag_actual)
            {
                
    $links_navegacao .= '<li><strong>' $i '</strong></li>'
            }
            
            else 
            {
                
    $links_navegacao .= '<li><a href="' $nome_pagina '?pagina=' $i '">'.$i.'</a></li>'
            }
        }    
                
        
    /*
         * @menu: link seguinte
         */    
        
    if ($pag_actual $ultima_pagina)
        {
            
    $links_navegacao .= '<li><a href="' $nome_pagina '?pagina=' . ($pag_actual 1) . '">Seguinte</a></li>';
        }
        
        
         
    ?>
    And finally, the HTML part of it:
    HTML Code:
    <html>
    <body>
    	
    	<table>
    		<?php echo $conteudo; ?>
    	</table>
    	<ul><?php echo $links_navegacao; ?></ul>
    		
    </body>
    I don't like it. I like this html part, quite nice. But I don't like the php part of listAssociacao.php. To big. Mixes DAO with presentation and pagination logic... :s messy.

    Maybe I should leave the static pagination method call, and put some private properties on my pagination class, add a few more public methods ?

    I'd love to separate the visual creation of the menu ($links_navegacao) and content ($conteudo) but I need some kick off tips on how to achieve that separation, if and only if, :-) it's possible to do that, without raise all the progress done till now...


    If someone feels like to give me a hand, I do appreciate. If not, it's ok. I will stay with this for now.

    Regards, and a big thanks for the help till now. I know it's not good, but I fill some progress on this.

    Márcio

  13. #38
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Quote Originally Posted by oikram
    I'd love to separate the visual creation of the menu ($links_navegacao) and content ($conteudo) but I need some kick off tips on how to achieve that separation, if and only if, :-) it's possible to do that, without raise all the progress done till now...
    You could code it into the pagination class or create a separate class responsible for handling the display of the pagination menu.

  14. #39
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by oddz View Post
    or create a separate class responsible for handling the display of the pagination menu.
    I will give it a try on creating a separate class. Using a method that will get the data from the pagination class and with that, construct the links and return the $menu;
    The same principle will be applied to the $content.

    I will give it a try.

    Regards,
    Márcio

  15. #40
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    This is the full pagination class I posted previously.

    You should see not only does it handle calculations but builds the menus using methods such as: makeMenu(), makeDropDown() and dropDownJavascript().

    The makeMenu() and makeDropDown() methods in particular accept a string as a url and replace {page} with the page for the link. The class is also responsible for determining which links are active, inactive and current.

    All this can be accomplished without dependencies on a model. Its just a numbers game.

    PHP Code:
    <?php
    class Pagination {
        
        
    // total number of records per page
        
    private $_count;
        
        
    // offset from beginning
        
    private $_offset;
        
        
    // current page
        
    private $_page;
        
        
    // total number of records with pagination
        
    private $_total;
        
        
    // number of controls to show from current page
        
    private $_range 1;
        
        public function 
    __construct($pCount,$pTotal,$pPage) {
            
    $this->_count $pCount?$pCount:10;
            
    $this->_total $pTotal;
            
    $this->_page $pPage?$pPage:1;
            
    $this->_currentPage();
            
    $this->_currentOffset();
        }
        
        private function 
    _currentOffset() {
            
            
    $page $this->_page;
            
    $this->_offset $this->_page==1?0:$this->_count*(--$page);
            
        }
        
        private function 
    _currentPage() {
            
            
    // send user to last page if they have gone past the total number of pages in the path variable
            
    if($this->_page>$this->pages()) {
                
    $this->_page $this->pages();
            }
            
        }
        
        
    // number of pages
        
    public function pages() {
            
    /*
             * if the count excedes the the total number than set 
             * the default to 1 page. There are less records than
             * will fit on one whole page.
             */
             
             
    return $this->_count>=$this->_total?1:ceil($this->_total/$this->_count);
        }
        
        public function 
    getOffset() {
            return 
    $this->_offset;
        }
        
        public function 
    getCount() {
            return 
    $this->_count;
        }
        
        public function 
    getPage() {
            return 
    $this->_page;
        }
        
        public function 
    getTotal() {
            return 
    $this->_total;
        }
        
        public function 
    getFirstPage() {
        
            return 
    1;
        
        }
        
        public function 
    firstPageActive() {
            
            return 
    $this->getFirstPage() == $this->getPage()?false:true;
        
        }
        
        public function 
    getPreviousPage() {
        
            return 
    $this->getPage()-1;
            
        
        }
        
        public function 
    hasPreviousPage() {
        
            
    $previousPage $this->getPreviousPage();
            
            return 
    $previousPage>=1?true:false;
        
        }
        
        public function 
    previousPageActive() {
            
            return 
    $this->hasPreviousPage();
        
        }
        
        public function 
    getNextPage() {
        
            return 
    $this->getPage()+1;
        
        }
        
        public function 
    hasNextPage() {

            
    $nextPage $this->getNextPage();
            
            return 
    $nextPage <= $this->pages()?true:false;    
        
        }
        
        public function 
    nextPageActive() {
            
            return 
    $this->hasNextPage();
        
        }
        
        public function 
    getLastPage() {
        
            return 
    $this->pages();
        
        }
        
        public function 
    lastPageActive() {
            
            return 
    $this->getLastPage() == $this->getPage() ? false true;
        
        }
        
        public function 
    getRange() {
        
            
    $min $this->getPage()-1;
            
    $max $this->getPage()+1;
            
            if(
    $min<1) {
                
    $min=1;
            }
            
            if(
    $max>$this->pages()) {
                
    $max=$this->pages();
            }
            
            return 
    range($min,$max,1);
        
        }
        
        public function 
    firstPageLink($pHref,$pLabel='First') {
        
            
    $href preg_replace('/{page}/',$this->getFirstPage(),$pHref);
        
            return 
    '<a class="active" href="'.$href.'">'.$pLabel.'</a>';
        
        }
        
        public function 
    firstPageButton($pHref,$pLabel='First') {
        
            if(
    $this->firstPageActive()===true) {

                return 
    $this->firstPageLink($pHref,$pLabel);

            } else {

                return 
    '<span class="inactive">'.$pLabel.'</span>';

            }
        
        }
        
        
        public function 
    previousPageLink($pHref,$pLabel='Previous') {
        
            
    $href preg_replace('/{page}/',$this->getPreviousPage(),$pHref);
        
            return 
    '<a class="active" href="'.$href.'">'.$pLabel.'</a>';
        
        }
        
        public function 
    previousPageButton($pHref,$pLabel='Previous') {
        
            if(
    $this->previousPageActive()===true) {

                return 
    $this->previousPageLink($pHref,$pLabel);

            } else {

                return 
    '<span class="inactive">'.$pLabel.'</span>';

            }
        
        }
        
        public function 
    nextPageLink($pHref,$pLabel='Next') {
        
            
    $href preg_replace('/{page}/',$this->getNextPage(),$pHref);
        
            return 
    '<a class="active" href="'.$href.'">'.$pLabel.'</a>';
        
        }
        
        public function 
    nextPageButton($pHref,$pLabel='Next') {
        
            if(
    $this->nextPageActive()===true) {

                return 
    $this->nextPageLink($pHref,$pLabel);

            } else {

                return 
    '<span class="inactive">'.$pLabel.'</span>';

            }
        
        }
        
        public function 
    lastPageLink($pHref,$pLabel='Last') {
        
            
    $href preg_replace('/{page}/',$this->getLastPage(),$pHref);
        
            return 
    '<a class="active" href="'.$href.'">'.$pLabel.'</a>';
        
        }
        
        public function 
    lastPageButton($pHref,$pLabel='Last') {
        
            if(
    $this->lastPageActive()===true) {

                return 
    $this->lastPageLink($pHref,$pLabel);

            } else {

                return 
    '<span class="inactive">'.$pLabel.'</span>';

            }
        
        }
        
        public function 
    pageLinks($pHref,$pHighlightCurrent=true,$pCurrentClass='current') {
        
            
    $str '<ul class="pages">'."\n";
            foreach(
    $this->getRange() as $range) {
                if(
    $pHighlightCurrent===true && $range==$this->getPage()) {
                    
    $str.= '<li><span class="'.$pCurrentClass.'">'.$range.'</span></li>'."\n";
                } else {
                
                    
    $href preg_replace('/{page}/',$range,$pHref);
                    
    $str.= '<li><a href="'.$href.'">'.$range.'</a></li>'."\n";
                }
            }
            return 
    $str."\n".'</ul>';
        
        }
        
        public function 
    firstPreviousModule($pHref) {
        
            
    $str '<ul>'."\n";
            
            
    $str.= "\t".'<li>'.$this->firstPageButton($pHref).'</li>'."\n";
            
    $str.= "\t".'<li>'.$this->previousPageButton($pHref).'</li>'."\n";
            
            
    $str.= '</ul>'."\n";
            
            return 
    $str;
        
        }
        
        public function 
    nextLastModule($pHref) {
        
            
    $str '<ul>'."\n";
            
            
    $str.= "\t".'<li>'.$this->nextPageButton($pHref).'</li>'."\n";
            
    $str.= "\t".'<li>'.$this->lastPageButton($pHref).'</li>'."\n";
            
            
    $str.= '</ul>'."\n";
            
            return 
    $str;
        
        }
        
        public function 
    makeMenu($pHref,$attr='') {
        
            
    $str '<ul'.$attr.'>'."\n";
            
            
    $str.= '<li>'."\n";
            
    $str.= $this->firstPreviousModule($pHref);
            
    $str.= '</li>'."\n";
        
            
    $str.= '<li>'."\n";
            
    $str.= $this->pageLinks($pHref);
            
    $str.= '</li>'."\n";
            
            
    $str.= '<li>'."\n";
            
    $str.= $this->nextLastModule($pHref);
            
    $str.= '</li>'."\n";    
            
            
    $str.= '</ul>'."\n";
            
            return 
    $str;
        
        }
        
        public function 
    makeDropDown($pHref,$pId) {
        
            
    $pages $this->pages();
            
            
    $str '<select id="'.$pId.'">'."\n";
            for(
    $i=1;$i<=$pages;$i++) {
                
                
    $value preg_replace('/{page}/',$i,$pHref);
                if(
    $this->getPage()==$i) {
                    
    $str.= "\t".'<option value="'.$value.'" selected="selected">'.$i.'</option>'."\n";    
                } else {
                    
    $str.= "\t".'<option value="'.$value.'">'.$i.'</option>'."\n";    
                }
            }
            
    $str.= '</select>'."\n";
            
            return 
    $str;
        
        }
        
        public function 
    dropDownJavascript($pId) {
            
            
    ?>
            var el = document.getElementById('<?php echo $pId ?>');
            el['onclick'] = function(pEvt) {

            var e = pEvt || event;
            target = e.target || e.srcElement;
                
            if(target.nodeName!='OPTION') { return; }
        
                window.location = target.getAttribute('value');
                
            }
            <?php
        
        
    }
        
    }
    ?>

  16. #41
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Example of output from makeMenu():

    HTML Code:
    <ul id="nav-pages">
    	<li>
    		<ul>
    			<li><span class="inactive">First</span></li>
    			<li><span class="inactive">Previous</span></li>
    		</ul>
    	</li>
    	<li>
    		<ul class="pages">
    			<li><span class="current">1</span></li>
    			<li><a href="/index.php/projects/2">2</a></li>
    		</ul>
    	</li>
    	<li>
    		<ul>
    			<li><a class="active" href="/index.php/projects/2">Next</a></li>
    			<li><a class="active" href="/index.php/projects/3">Last</a></li>
    		</ul>
    	</li>
    </ul>
    Example of output from makeDropDown():

    HTML Code:
    <select id="pagination-drop-down">
    	<option value="/index.php/projects/1" selected="selected">1</option>
    	<option value="/index.php/projects/2">2</option>
    	<option value="/index.php/projects/3">3</option>
    </select>
    Example of output from dropDownJavascript():

    Code JAVASCRIPT:
    		var el = document.getElementById('pagination-drop-down');
    		el['onclick'] = function(pEvt) {
     
    		var e = pEvt || event;
    		target = e.target || e.srcElement;
     
    		if(target.nodeName!='OPTION') { return; }
     
    			window.location = target.getAttribute('value');
     
    		}

    The JavaScript would be placed in a function to be called upon page load separated from the structure of the document ideally.

    The above is just all a matter of two calls in the PHP view code:

    PHP Code:
    echo $pagination->makeMenu($url,' id="nav-pages"');
    echo 
    $pagination->makeDropDown($url,'pagination-drop-down'); 

  17. #42
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Off Topic:

    Quote Originally Posted by oikram View Post
    I have no more then several months on PHP and programming in general
    I'm impressed.

  18. #43
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by crmalibu View Post
    Off Topic:


    I'm impressed.
    Don't be. I'm still very dummy and unable to actually found programmatic solutions to a problem. I'm starting to learn how to read others code and *almost* understand them. But I'm still unable to create my own programmatic solutions based on a problem. And I have gaps on my knowledge. Till yesterday I didn't know the difference between == and = still, I have create a Singleton PDO connection class. So well... :s Weird.

    Btw, each time I see oddz replys my dummy level raises a lot! So... well... I'm not impressed by my level.

    However, I'm impress by what I've just done. After reading last oddz post, I've moved from the code I was having to this one:



    So, now here it is a new Pagination class:

    PHP Code:
    <?php


    class Paginacao 
    {
        
        private 
    $_pag_actual;
        
        private 
    $_ultima_pagina;
        
        private 
    $_limit;
        
        private 
    $_offset;

        

        public function 
    getPaginaActual()
        {
            
            if (
    $this->_pag_actual $this->_ultima_pagina)
            {
                
                
    $this->_pag_actual $this->_ultima_pagina;
            }
            
            else if (
    $this->_pag_actual 1)
            {
                
                
    $this->_pag_actual 1;
            }
            
            if (
    filter_has_var(INPUT_GET'pagina') == false
            {
                
    $this->_pag_actual 1;
            }
                else 
            {
                
    $this->_pag_actual = (int)$_GET['pagina'];
            }
            
            return 
    $this->_pag_actual;
        }
        
        
        public function 
    getUltimaPagina($total_registos)    
        {
            
    $this->_ultima_pagina ceil($total_registos $this->_limit);
            
            return 
    $this->_ultima_pagina;
        }
        
        
        public function 
    getLimit()
        {
            
            if (
    filter_has_var(INPUT_GET'limit') == true
            {
                
    $this->_limit = (int)$_GET['limit'];        
            }
            else
            {
            
                
    $this->_limit 3;
            }
            
            return 
    $this->_limit;
        }
        
        
        public function 
    getOffset()
        {    
            
            
    $this->_offset = ($this->_pag_actual 1) * $this->_limit;

            return 
    $this->_offset;
            
        } 

        
        
        
        public function 
    getContent($records)
        {
            
    $conteudo '';
        
            foreach(
    $records as $record)
            {
                    
                
    $conteudo .= '
                    <tr>
                        <td>' 
    $record->nome_associacao '</td>
                        <td>' 
    $record->telefone_associacao .'</td>
                    </tr>'

            }
            
            return 
    $conteudo;
        }
        
        
        
        public function 
    getLinks()
        {

            
    $links_navegacao='';

            
    $nome_pagina htmlentities($_SERVER['PHP_SELF']);
                    
            
    /*first and previous links*/
            
    if($this->_pag_actual 1
            {
                
    $links_navegacao '<li class="primeiro"><a href="' $nome_pagina '?pagina=1">Primeiro</a></li>';
                 
    $links_navegacao .= '<li class="anterior"><a href="' $nome_pagina '?pagina=' . ($this->_pag_actual 1) . '">&laquo; Anterior</a></li>';
            } 
            else if (
    $this->_pag_actual == 1)
            {
                
    $links_navegacao .= '<li class="primeiro-off">Primeiro</li>';
                
    $links_navegacao .= '<li class="anterior-off">&laquo; Anterior</li>';        
            } 
            
            
    /*numbers*/
            
    $i=null;
            
    $range=1;

            for (
    $i = (($this->_pag_actual $range) - 1); $i < (($this->_pag_actual $range) + 1); $i++)
            {
                if ((
    $i 0) && ($i <= $this->_ultima_pagina)) {
            
                    if (
    $i == $this->_pag_actual)
                    {
                        
    $links_navegacao .= '<li class="activo"><strong>' $i '</strong></li>'
                    }
                
                    else 
                    {
                        
    $links_navegacao .= '<li><a href="' $nome_pagina '?pagina=' $i '">'.$i.'</a></li>'
                    }
                }
            }    
                    
            
    /*next and last links*/
            
    if ($this->_pag_actual $this->_ultima_pagina)
            {
                
    $links_navegacao .= '<li class="seguinte"><a href="' $nome_pagina '?pagina=' . ($this->_pag_actual 1) . '">Seguinte &raquo;</a></li>';
                
    $links_navegacao .= '<li class="ultimo"><a href="' $nome_pagina '?pagina=' . ($this->_ultima_pagina) . '">Último</a></li>';
            } 
            
            else if (
    $this->_pag_actual == $this->_ultima_pagina)
            {
                
    $links_navegacao .= '<li class="seguinte-off">Seguinte &raquo;</li>';
                
    $links_navegacao .= '<li class="ultimo-off">Último</li>';
            } 
            
            return 
    $links_navegacao;
            
        }    
    }
    //fim da classe

    ?>

    And here it is the php part of listAssociacao.php:
    PHP Code:
    <?php
        
        
    require_once("AssociacaoDAO.class.php");
        require_once(
    "Paginacao.class.php");
        
        
        
    /* @instanciamentos */
        
    $associacao_dao = new AssociacaoDAO();
        
    $pag = new Paginacao();
        
        
    //current_page
        
    $pag_actual $pag->getPaginaActual();
        
        
    //total_records
        
    $total_registos $associacao_dao->contar();
        
        
    //limit
        
    $limit $pag->getLimit();
        
        
    //last_page
        
    $ultima_pagina $pag->getUltimaPagina($total_registos->total);
        
        
    //offset
        
    $offset $pag->getOffset();
        
        
    /* get records from our DAO */
        
    $records=$associacao_dao->listar($offset$limit);
        
        
    //get content based on records, that are based on listar method, that needs $offset and $limit
        
    $conteudo $pag->getContent($records);
        
        
    $links_navegacao $pag->getLinks();
             
    ?>
    And the html part of listAssociacao.php, stays as before:
    HTML Code:
    <body>
    	
    	<table>
    		<?php echo $conteudo; ?>
    	</table>
    	<ul id="paginacao"><?php echo $links_navegacao; ?></ul>
    		
    </body>

    It's better, I believe , however:
    1. I've moved the content part to the pagination. I've moved to much!!

    1. I still need a bunch of code on listAssociacao.php, just because I need to:
      PHP Code:
      /* get records from our DAO */
      $records=$associacao_dao->listar($offset$limit); 


    Without creating all new from scratch, where should I put the content generation part ?

    I need to nicely separate my DAO from my pagination, after all, I will have one pagination to list associations, another pagination to list dogs, etc...


    Thanks a lot,
    M&#225;rcio


    ps-Just wondering... Am I doing a loop on this pagination question?

  19. #44
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok... I have re arrange the pagination class, and hopefully I'm closer to an MVC pattern:

    Supposing that the M part is my DAO.

    And my C part is my pagination class:
    (This pagination class contains no visual generation elements):

    PHP Code:
    <?php


    class Paginacao 
    {
        
        private 
    $_pag_actual;
        
        private 
    $_ultima_pagina;
        
        private 
    $_limit;
        
        private 
    $_offset;

        

        public function 
    getPaginaActual()
        {
            
            if (
    $this->_pag_actual $this->_ultima_pagina)
            {
                
                
    $this->_pag_actual $this->_ultima_pagina;
            }
            
            else if (
    $this->_pag_actual 1)
            {
                
                
    $this->_pag_actual 1;
            }
            
            if (
    filter_has_var(INPUT_GET'pagina') == false
            {
                
    $this->_pag_actual 1;
            }
                else 
            {
                
    $this->_pag_actual = (int)$_GET['pagina'];
            }
            
            return 
    $this->_pag_actual;
        }
        
        
        public function 
    getUltimaPagina($total_registos)    
        {
            
    $this->_ultima_pagina ceil($total_registos $this->_limit);
            
            return 
    $this->_ultima_pagina;
        }
        
        
        public function 
    getLimit()
        {
            
            if (
    filter_has_var(INPUT_GET'limit') == true
            {
                
    $this->_limit = (int)$_GET['limit'];        
            }
            else
            {
            
                
    $this->_limit 3;
            }
            
            return 
    $this->_limit;
        }
        
        
        public function 
    getOffset()
        {    
            
            
    $this->_offset = ($this->_pag_actual 1) * $this->_limit;

            return 
    $this->_offset;
            
        } 
        
        
    /*A getLinks e getContent foram removidas, e estamos a tratar apenas dos links em si:*/
        
    public function paginaAnterior()
        {
            return 
    $this->_pag_actual 1;
        }
        
        public function 
    paginaSeguinte()
        {
            return 
    $this->_pag_actual 1;
        }
        
        public function 
    temPaginaAnterior()
        {
            
    /*
             * Verifica se o método pag_anterior() vai devolver um valor maior ou igual a 1. Se sim, então devolve TRUE. 
             * Caso contrário (:) devolve FALSE. 
             */
            
    return $this->paginaAnterior() >= true false;
        }
        
        public function 
    temPaginaSeguinte()
        {
            return 
    $this->paginaSeguinte() <= $this->_ultima_pagina true false;
        }    
        
        public function 
    estaUltimaPagina()
        {
            
    /*
             * Se o atributo $_pag_actual for igual ao atributo , devolve true, caso contrário, devolve falso.
             */
            
    return $this->_pag_actual == $this->_ultima_pagina true false;     
        }
        
        public function 
    estaPrimeiraPagina()
        {
            return 
    $this->_pag_actual == true false;     
        }
        
    public function 
    getNomePagina() 
        {
            
    $this->_nome_pagina htmlentities($_SERVER['PHP_SELF']);
            
            return 
    $this->_nome_pagina;
        }
        
    }
    //fim da classe

    Then I have a View part, like this:

    O listaAssociacao.php:

    PHP Code:
    <?php
        
        
    require_once("AssociacaoDAO.class.php");
        require_once(
    "Paginacao.class.php");
        
        
        
    /* @instanciamentos */
        
    $associacao_dao = new AssociacaoDAO();
        
    $pag = new Paginacao();
        
        
    //current_page
        
    $pag_actual $pag->getPaginaActual();
        
        
    //total_records
        
    $total_registos $associacao_dao->contar();
        
        
    //limit
        
    $limit $pag->getLimit();
        
        
    //last_page
        
    $ultima_pagina $pag->getUltimaPagina($total_registos->total);
        
        
    //offset
        
    $offset $pag->getOffset();
        
    //nome da pagina:
    $nome_pagina $pag->getNomePagina();

        
        
    /* get records from our DAO */
        
    $records=$associacao_dao->listar($offset$limit);
        
        
    //gera conteúdo:
        
    $conteudo '';
        
            foreach(
    $records as $record)
            {
                    
                
    $conteudo .= '
                    <tr>
                        <td>' 
    $record->nome_associacao '</td>
                        <td>' 
    $record->telefone_associacao .'</td>
                    </tr>'

            }

        
    //gera links de navegacao:
        
    $links_navegacao='';
        
        
    //links primeiro e anterior:
    if($pag->temPaginaAnterior()) 
        {
        
    $links_navegacao '<li class="primeiro"><a href="' $nome_pagina '?pagina=1">Primeiro</a></li>';
        
    $links_navegacao .= '<li class="anterior"><a href="' $nome_pagina '?pagina=' . ($pag->paginaAnterior()) . '">&laquo; Anterior</a></li>';
        }
        else if (
    $pag->estaPrimeiraPagina())
        {
            
    $links_navegacao .= '<li class="primeiro-off">Primeiro</li>';
            
    $links_navegacao .= '<li class="anterior-off">&laquo; Anterior</li>';        
        }

         
    /*links numéricos*/
        
    $i=null;
        
    $range=1;

        for (
    $i = (($pag_actual $range) - 1); $i < (($pag_actual $range) + 1); $i++)
        {
            if ((
    $i 0) && ($i <= $ultima_pagina)) {
        
                if (
    $i == $pag_actual)
                {
                    
    $links_navegacao .= '<li class="activo"><strong>' $i '</strong></li>'
                }
            
                else 
                {
                    
    $links_navegacao .= '<li><a href="' $nome_pagina '?pagina=' $i '">'.$i.'</a></li>'
                }
            }
        }

    /*next and last links*/
    if($pag->temPaginaSeguinte()) 
        {
            
    $links_navegacao .= '<li class="seguinte"><a href="' $nome_pagina '?pagina=' . ($pag->paginaSeguinte()). '">Seguinte &raquo;</a></li>';
            
    $links_navegacao .= '<li class="ultimo"><a href="' $nome_pagina '?pagina=' $ultima_pagina '">Último</a></li>';
        } 
            
        else if (
    $pag->estaUltimaPagina())    {
            
    $links_navegacao .= '<li class="seguinte-off">Seguinte &raquo;</li>';
            
    $links_navegacao .= '<li class="ultimo-off">Último</li>';
        } 
    ?>    

    <!—the html part-->
    <body>
        
        <table>
            <?php echo $conteudo?>
        </table>
        <ul id="paginacao"><?php echo $links_navegacao?></ul>
            
    </body>
    I'd like to implement a template system. I don't want to use smarty neither an existing framework for that propose.

    Should we put some part of this "view page" on a template ?

    Thanks a lot,
    Márcio


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •