Hi folks-
I am currently working on a PHP application which I am using as a
personal learning environment for getting a better working
understanding about how to tackle application development in an OOP/MVC
pattern fashion.
I am using PEAR::DB to create database connection objects, and my major
question concerns where these objects should be created.
For example: Let's say I have a login application that that has a
controller-like script that looks something like this:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// login.php
<?php
require_once('User.class.php');
$user = new $User;
$user->getAdminRights();
?>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
....and a model-like User class that looks something like this: (The
important note is that I may need to load data multiple times from a
database.)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// User.class.php
<?php
class User
{
public $user_name;
public $user_id;
public $admin_rights = array();
protected $db_connection;
function __construct()
{
if (!this->db_connection){
require_once();
$this->db_connection = DB::connect(DB_DSN);
}
$sql = "SELECT USERNAME, USER_ID FROM SOME_TABLE...";
$result = $this->dbh->getAll($sql, array($this->request_id);
$this->user_name = $result['USERNAME'];
$this->user_id = $result['USER_ID'];
}
function getAdminRights()
{
$sql = "SELECT * FROM SOME_TABLE WHERE ADMIN_ID = ?";
$this->admin_rights = $this->dbh->getAll($sql,
array($this->user_id);
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As you may see, I am creating an instance of a database object as an
attribute of the User class itself.
This seems to have benefits like:
-- Keeps data manipulation out of the controller (and away from having
to global a db object if I had created it on the login.php page)
And also drawbacks like:
-- Not exactly an example of loose coupling in the above example.
I'd greatly appreciate some feedback from experienced PHP OOP
developers about the best way to tackle this problem. :)
Where to create database objects for use with classes?
TIA-
Shawn C.