Jump to content

Want to make code reusable; not sure how to deal with pagination data...


cgm225

Recommended Posts

I have a notes/blog class I am using in which I put data from a database into an array, and then display a certain number of those entries per page based on a number (the $numberDisplayed variable).  I also calculate the total number of pages, and the first and last entry, based on that variable for use in my pagination.

 

My question is this, now I am working on a gallery app (with a similar MVC helper class, Gallery class, and currently using the same numberDisplay class included lastly below), and I find I am simply copying and pasting most of my blog helper class code; therefore, is there any way you would suggest I could code this app to be more generic and reusable, such that I could use one function/class to generate pagination data for any application?  I don't want to be copying/pasting code, but, at the same time, I was not sure how to best do things?  This was a related post, but I was not sure if simply making a function that way was the best solution.

 

Thanks in advance for the help.

 

 

 

 

 

 

 

My MVC helper class in which I instantiate the new notes class and calculate all that data outlined above::

<?php

class NotesActions extends ActionController {
    
    public function doNotes() {

        //Includes then instatiates new Notes class
        require_once $this->pageDir . '/' . $this->getModule() . '/' . 'includes/Notes.php5';
        $notes = new Notes($mysqli);

        //Sets page variable
        $regex = '/[^0-9]++/'; //Only numbers allowed
        $page = isset($_GET['page']) ? preg_replace($regex, '', $_GET['page']) : 1;
        
        //Adds total number of entries to the registry
        $this->registry->set('totalEntries', $notes->getDataCount());        
        
        //Includes/instantiates class to specify number displayed per page
        require_once $this->pageDir . '/NumberDisplayed.php5';
        $numberDisplayed = new NumberDisplayed('notes', 2);
        
        //Adds numberDisplayed per page variable to the registry
        $numberDisplayed = $numberDisplayed->getNumberDisplayed();
        $this->registry->set('notesDisplayed', $numberDisplayed);
        
        //Calculates total number of pages and adds value to the registry
        $totalPages = ceil($notes->getDataCount() / $numberDisplayed);
        $this->registry->set('totalPages', $totalPages);
        
        /* Resets page number to total number of pages if current page value is
         * greater than total pages
         */ 
        $page = ($page > $totalPages) ? $totalPages : $page;
        
        //Adds final page value to the registry
        $this->registry->set('page', $page);

        /* Calculates position of the first and last entry within the data array
         * for any partciular page and adds those values to the registry 
         */
        $firstPageEntry = ($page * $numberDisplayed) - $numberDisplayed;
        $lastPageEntry  = $firstPageEntry + $numberDisplayed;
        $this->registry->set('firstPageEntry ', $firstPageEntry);
        $this->registry->set('lastPageEntry', $lastPageEntry);
       
        //Passes data array to the registry
        $this->registry->set('notes', $notes->getSlicedData($firstPageEntry, $numberDisplayed));

    }
}

?>

 

My Notes class:

<?php

class Notes {
    
    //Declaring variables
    private $connection;
    private $id;
    private $data = array();
    
    //Sets MySQLi object
    public function __construct(mysqli $connection) {
        $this->connection = $connection;
    }
    
    /* Creates a two dimensional array in which entry id numbers are stored in
     * the first dimension, and then for each id number, a second array (i.e.
     * the second dimension) is assigned, which contains all the field values
     * for that particular entry.
     */
    public function findEntries() {
        $query = 'SELECT id, title, note, date, timestamp FROM notes ORDER BY id DESC';
        $statement = $this->connection->prepare($query);
        $statement->bind_result($id, $title, $note, $date, $timestamp);
        $statement->execute();
        while($statement->fetch()) {
            $this->data[$id] = array(
                'id'         => $id,
                'title'      => $title,
                'date'       => $date,
                'note'       => $note,
                'timestamp'  => $timestamp
            );
        }
        $statement->close();
    }
    
    //Returns the data array
    public function getData() {
        if (!empty($this->data)){
            return $this->data;
        } else {
            return false;
        }
    }
    
    //Returns the number of items in the data array
    public function getDataCount() {
        if (!empty($this->data)){
            return count($this->data);
        } else {
            return false;
        }
    }
    
    //Returns a particular range of the data from the data array
    public function getSlicedData($offset = 0, $length = 10000) {
        if (!empty($this->data)){
            return array_slice(array_values($this->data), $offset, $length);
        } else {
            return false;
        }
    }
}

?>

 

My numberDisplayed class::

<?php

class NumberDisplayed {
    
    //Declaring variables
    private $arrayKey;
    private $defaultDisplayNumber;
    private $numberDisplayed;

    public function __construct($arrayKey, $defaultDisplayNumber) {
        
        //Sets variables
        $this->arrayKey = $arrayKey;
        
        //Creates numberDisplayed array session variable if not already present 
        if (!isset($_SESSION['numberDisplayed'])) {
            $_SESSION['numberDisplayed'] = array();
        }
        
        /* If user has provided a new number to display from an HTML form, that
         * value will be added/updated in the numberDisplayed array session
         * variable.  If no new value has been provided, then, if the key is
         * present, the existing session variable key/value pair will be used,
         * or a new pair will be created based on a provided default value
         */ 
        if (isset($_POST['numberDisplayed'])) {
            $this->setNumberDisplayed($this->arrayKey, $_POST['numberDisplayed']);
        } elseif (!$this->getNumberDisplayed('notes')) {
            $this->setNumberDisplayed($this->arrayKey, $defaultDisplayNumber);
        }
        
    }
    
    public function setNumberDisplayed($arrayKey, $numberDisplayed) {
        
        //Checks that the $numberDisplayed variable only contains numbers
        $regex = '/[^0-9]++/'; //Only numbers allowed
        $this->numberDisplayed = preg_replace($regex, '', $numberDisplayed);
        
        //Adds key/value pair to session array
        $_SESSION['numberDisplayed'][$arrayKey] = $this->numberDisplayed;
        
    }
    
    public function getNumberDisplayed() {
        
        //Either returns the key's value or returns false
        if (empty($_SESSION['numberDisplayed'][$this->arrayKey])) {
            return false;   
        } else {
            return $_SESSION['numberDisplayed'][$this->arrayKey];
        }
        
    }

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.