1

I've got a PHP project with many classes, and a PDO Wrapper class that I got off the web that seems pretty good:

http://code.google.com/p/php-pdo-wrapper-class/

My classes look like this now:

class product {
__constructor($id = 0) {
//mysql_query and store the product row in $this->row;
}

edit($array) {
//another obvious mysql_query...
}

So they're very simple and I want to move all the mysql_query's to PDO for security. I've got the variable:

$db = new pdo('localhost', 'user', 'pass');

Working correctly defined in the top line of my include file, before the classes. However, I don't want to have to write:

global $db;

At the start of every function. I considered changing the __construct() function to be something more like:

__construct($id = 0, $db = null) {
$this->db = $db;
}

And then referencing from there, but the problem with that is that I then have to change every constructor in my whole website. Is there a way to solve this such that I am able to do the minuimum amount of editing the already existing code?

3 Answers 3

2

Make all your model classes inherit from a base model class, then define a static variable $db in your base class, and use it in the inherited classes.

class BaseModel {
  public static $db = NULL;
}

class UserModel extends BaseModel {
  public function create() {
    echo "Use the static variable: " . static::$db . "\n";
  }
}

BaseModel::$db = "new PDO object";
UserModel::create();

Outputs

Use the static variable: new PDO object
Sign up to request clarification or add additional context in comments.

3 Comments

It's not better than global variables
It's better in a sense that you don't have to say global $db inside of every function, and it's only "global" in BaseModel and its descendants rather than everywhere.
This appears better in that I would only have to make a tiny "BaseModel" class and then type "extends BaseModel" at the end of ten class files, which would make it essentially backwards compatible while I change all the database calls over. Thanks!
0

as you said there is a PDO class so in every other classes easily you can make an instance of your PDO class. first include the PDO class in anywhere you need

require_once'/PDOclass.php';

then make instances

$a=new PDAclass;

Comments

0

You say the $db is defined in your include file. so just include the file and you'll have access to that parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.