objects and memory

i’m building a basic cms in an oop fashion, as i later wan’t to try and extend it’s functionality and in the process learn some oop :slight_smile: If i’m treating pages and categories as objects, is it bad to pull in all pages to memory and use them as i wish or is it better to only bring in the objects i know i’ll need an any one time? obviously it’s quite convenient having them all there but does this have much of an effect on memory and site speed?
Thanks

Just a suggestion I would do is go with some kind of pattern (There are whole books devoted to patterns). I don’t use a pattern though there are a lot of people that will argue that it is (I’m not going to get into that debate ;D ) that is called MVC (Model-View-Control). As for reading in pages that is part of my iCRUD (interface Create-Read-Update-Delete) structure.

Here’s an example of mine -
[php]<?php

namespace website_project\blog;

/* Location of the ConnectPDO Class ($PDO Connection String) */

use website_project\database\ConnectPDO as ConnectPDO;
use PDO;
use DateTime;
use DateTimeZone;

class Blog implements iCRUD {

private $connectPDO;
private $pdo;
protected $query;
protected $stmt;
protected $sql;
protected $result;
protected $queryParams;
protected $author;
protected $username;
protected $category;
protected $enum;
protected $type;
protected $matches;
protected $vals;
public $categories = [];
protected $row;

public function __construct(ConnectPDO $connectPDO) {
    $this->connectPDO = $connectPDO;
    $this->pdo = $this->connectPDO->getDatabase();
}

public function displayDate($date) {
    $this->display = new DateTime($date, new DateTimeZone('America/Detroit'));
    echo $this->display->format("F j, Y g:i A");
}

public function create($data) {
    $this->query = "INSERT INTO pages (creator_id, category, title, content, date_added) VALUES (:creator_id, :category, :title, :content, NOW()) ";
    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->result = $this->stmt->execute([
            ':creator_id' => $data['creator_id'],
            ':category' => $data['category'],
            ':title' => $data['title'],
            ':content' => $data['content']
        ]);
        if ($this->result) {
            header("Location: forums.php");
            exit();
        }
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

public function read($category = "sysop") {
    $this->query = 'SELECT id, creator_id, category, sticky, title, content,  date_updated, date_added FROM pages WHERE category=:category ORDER BY date_added DESC';
    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->stmt->execute([':category' => $category]);
        $this->stmt->setFetchMode(PDO::FETCH_OBJ);
        return $this->stmt;
    } catch (Exception $ex) {
        print $ex->getMessage();
    }
}

public function update($data) {
    $this->query = 'UPDATE pages SET category=:category, title=:title, content=:content, date_updated=NOW() WHERE id=:id';
    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->result = $this->stmt->execute([':category' => $data['category'], ':title' => $data['title'], ':content' => $data['content'], ':id' => $data['id']]);
        if ($this->result) {
            return TRUE;
        }
    } catch (Exception $ex) {
        print $ex->getMessage();
    }
}

public function delete($id = NULL) {
    $this->query = "DELETE FROM pages WHERE id=:id";
    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->stmt->execute([':id' => $id]);
        header("Location: forums.php");
        exit();
    } catch (Exception $ex) {
        echo $ex->getMessage();
    }
}

public function scrub($raw_input) {
    return htmlspecialchars($raw_input, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
}

/* Grab the categories and put it into a category array */

public function getCategories() {
    /* Set up the query to fetch only the category column which is an enumerated type */
    $this->sql = "SHOW COLUMNS FROM pages LIKE 'category' ";
    $this->category = $this->pdo->query($this->sql);
    /* set it up as an object */
    $this->category->setFetchMode(\PDO::FETCH_OBJ);
    /* Fetch all the rows in that particular column as objects */
    $this->enum = $this->category->fetchAll();

    $this->type = $this->enum[0]->Type; // Grab only the Type column:

    preg_match('/enum\((.*)\)$/', $this->type, $this->matches); // Strip enum() away from the string:
    $this->vals = explode(',', $this->matches[1]); // Convert it to an array:

    /* Trim the ' away from the individual values and put it in categories array */
    foreach ($this->vals as $value) {
        $this->categories[] = trim($value, "'");
    }
    return $this->categories; // Return the array with the proper categories:
}

public function readSingleRecord($id) {
    $this->sql = "SELECT id, creator_id, sticky, title, content FROM pages WHERE id=:id LIMIT 1";
    try {
        $this->stmt = $this->pdo->prepare($this->sql);
        $this->stmt->execute([':id' => $id]);
        $this->result = $this->stmt->fetch(\PDO::FETCH_OBJ);
        return $this->result;
    } catch (Exception $ex) {
        print $ex->getMessage();
    }
}

public function getUsername($id) {

    $this->query = 'SELECT id, username, password, security_level, first_name, last_name FROM users WHERE id=:id';


    try {
        $this->stmt = $this->pdo->prepare($this->query);
        $this->stmt->execute([':id' => $id]);

        $this->stmt->setFetchMode(\PDO::FETCH_OBJ);
        $this->author = $this->stmt->fetch();
        $this->username = $this->author->first_name . ' ' . $this->author->last_name;
        return $this->scrub($this->username);
    } catch (Exception $ex) {
        die("Failed to run query: " . $ex->getMessage());
    }
}

}
[/php]

Sorry, it’s gotten kind of sloppy for I have been putting helper methods (functions) into the class as well. ::slight_smile: I should keep iCRUD and the helper methods separated, but even I get lazy at times. :smiley: I look at OOP as a way to keep things separated, organized, easy to maintained and reusable. It will starts becoming really reusable when you start using namespaces.

Pulling the text from the database one usually does not have to worry about memory problems, plus if one ever gets into Ajax/JSON then it’s very easy to do. Another suggestion get the PHP portion done first, then concentrate on the Ajax/JSON portion. You’ll find it better structured, easier to maintain and even better secured for you won’t be mixing in PHP and JavaScript in as much. Specially with database calls.

Oh yeah, I probably should show the interface class (It’s very simple) :
[php]<?php
namespace website_project\blog;

/* The iCrud interface.

  • The interface identifies four methods:
    • create()
    • read()
    • update()
    • delete()
      */
      interface iCRUD {

public function create($data);

public function read();

public function update($data);

public function delete($id=NULL);

}[/php]

All it basically does is it forces you to be structured, well that’s the way I look at it. :wink:

Ok, cheers. So it’s kinda pointless instantiating pages? better to just read from the fetch results? i have looked a little at ajax through the jquery functions. I didn’t realize you could use it to fetch data from a database? i checked it out briefly, just loading in content from a file.

Sponsor our Newsletter | Privacy Policy | Terms of Service