473,804 Members | 3,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OOP database tables <-> php interface (semi LONG)

Hi,

I'm trying to grasp OOP to build an interface using class objects that lets
me access database tables easily. You have probably seen this before, or
maybe even built it yourself at some point in time. I have studied some
examples I found on the internet, and am now trying to build my own from
scratch.

I have made a default table class (DB_Table), a default validation class
(Validator) which is an object inside DB_Table and my final database tables
each get a class: e.g. User, UserProfile, Country, etc that extend the
DB_Table class.

Its something along the lines of (incomplete code, just for demonstration
purpose):

<?php

class DB_Table
{
public function __construct()
{
// intialize object
// initialize (common) validator
$this->validator = new Validator( $this );
}

public function loadData()
{
// get all data from record
}

public function saveData()
{
// save all data to record
}

public function __get( $field )
{
// get object property
}

public function __set( $field, $value )
{
// set object property
}
}

class User extends DB_Table
{
public $dbt = DB_TABLE_USER;

public $fields = array(
'id' =NULL,
'userType' =NULL,
'username' =NULL,
'password' =NULL,
'email' =NULL,
'active' =NULL,
'timeCreated' =NULL,
'timeActivated' =NULL,
'timeUpdated' =NULL
);

public $fieldSpecs = array(
'id' =array(
'screenname' ='user id',
'type' ='int',
'autoinsert' =true,
'autoincrement' =true,
'static' =true
),
'userType' =array(
'type' ='tyniint',
'nodisplay' =true
),
'username' =array(
'screenname' ='username',
'type' ='string',
'unique' =true,
'required' =true,
'static' =true,
),
// etc...
);
}

?>

It definately still needs a lot of tayloring for it to even work smoothly
for straightforward DB tables. But besides that, a few future issues are
bothering me already:

For instance, take the class User: let's say somebody registers at my site.
This person fills in the details. The Validator class checks each field
seperately. No problem. A new User record is inserted in the database.

But what now, if a user wants to login to the system after the user is
registrated?
I would create an instance of class User. Asign the credential values to the
object. And let the Validator class do its work again.
But, if a user logs in with incorrect credentials, I don't want to report
back to the user whether he/she filled in an incorrect username or an
incorrect password. No, I only want to report back that he/she has filled in
wrong credentials.

But the Validator class only checks each field seperately. In order to keep
the Validator class as common as possible would you build a seperate Login
class for instance? A class that has some custom validation methods? Or
perhaps just insert custom validation methods in the User class? I myself
just cannot seem to make up my mind in this case. Probably cause I'm still
too inexperienced when it comes to OOP programming.

A few other minor questions come to mind also:
- My gut feeling tells me it is wise to make a reference to the Validator
class inside DB_Table, e.g:
$this->validator =& new Validator( $this );
.... because it only creates a single instance of the object, right?

- And why can't I refer to a private variable in DB_Table from an extended
class (such as User)? I would asume, that this private variable, declared in
the parent object, is now a private variable in User also, no?

- And last but not least, is there a way for me to access let's say User
properties from the Validator class without having to pass $this as an
argument to:
$this->validator = new Validator( $this );
.... I know the following to be incorrect, but I was thinking of something
like the keyword parent.

I hope these questions and examples make sense to you and hopefully someone
can shed a light on these issues. Thank you in advance for your time.

Cheers
Apr 11 '07
22 3528

"Toby A Inkster" <us**********@t obyinkster.co.u kschreef in bericht
news:dc******** ****@ophelia.g5 n.co.uk...
amygdala wrote:
>Since I would like to have only one database handler that can be accessed
by
both the constructor and the factory method (?) getUserById() I decided
to
declare $dbh static. Does this make sense?

It makes sense, but a better solution would be to make your database
object into a singleton class. That is, similar to the Database object
here:

http://message-id.net/<r1************ @ophelia.g5n.co .uk>
Well, that is the case already. Perhaps it was a bit confusion because I
named the method in the Database object getInstance. I've changed it to
getSingleton now. (See below).

But that still doesn't allow me to create the $dbh only once at the
beginning of the User class like so:

class User
{
private $dbh = Database::getSi ngleton( /* */ );

private function __construct() {}

public static function getUserById()
{
// use self::$dbh here
}

public function saveUser()
{
// use self::$dbh here
}
}

Mind you, it's not a big issue, merely a cosmetic one. What I am still
struggeling more with is the registrate function. Would you consider that a
User class method. Or should it be in some other object. Or perhaps just be
a regular function in the global script?
// class Database code:

class Database
{
protected static $dbh;

private function __construct() {}

public static function getSingleton( $interface, $host, $schema, $username,
$password )
{
if ( !isset( self::$dbh ) )
{
self::$dbh = new PDO( ( $interface . ':host=' . $host . ';dbname=' .
$schema ), $username, $password );
self::$dbh->setAttribute ( PDO::ATTR_ERRMO DE, PDO::ERRMODE_EX CEPTION );
//self::$dbh->setAttribute ( PDO::MYSQL_ATTR _USE_BUFFERED_Q UERY, TRUE );
}
return self::$dbh;
}

public function __destruct()
{
if ( isset( self::$dbh ) )
{
self::$dbh = NULL;
}
}
}
Apr 16 '07 #21
amygdala wrote:
Mind you, it's not a big issue, merely a cosmetic one. What I am still
struggeling more with is the registrate function. Would you consider that a
User class method. Or should it be in some other object. Or perhaps just be
a regular function in the global script?
It could be implemented as a regular function, but I'd tend to put it as a
static factory function in the User class. (i.e. it returns the newly
registered User as an object -- much like the static login function
would.) This has the benefit of having internal consistency with the login
function. (A developer familiar with the login function would have little
trouble picking up the registration function.) Also, it keeps the function
"wrapped up" in the User class, so that everything is kept in one place.

--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

* = I'm getting there!
Apr 16 '07 #22

"Toby A Inkster" <us**********@t obyinkster.co.u kschreef in bericht
news:go******** ****@ophelia.g5 n.co.uk...
amygdala wrote:
>Mind you, it's not a big issue, merely a cosmetic one. What I am still
struggeling more with is the registrate function. Would you consider that
a
User class method. Or should it be in some other object. Or perhaps just
be
a regular function in the global script?

It could be implemented as a regular function, but I'd tend to put it as a
static factory function in the User class. (i.e. it returns the newly
registered User as an object -- much like the static login function
would.) This has the benefit of having internal consistency with the login
function. (A developer familiar with the login function would have little
trouble picking up the registration function.) Also, it keeps the function
"wrapped up" in the User class, so that everything is kept in one place.
Alright Toby, that is reassuring. Thanks for the input.
Apr 16 '07 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3061
by: lkrubner | last post by:
I have a webserver through Rackspace. I create a domain. I create an FTP user. I upload some files. I create a database called testOfSetupScript and then I create a database user named setup. I write some PHP code which should, I think, be able to to auto create the tables. The SQL looks like this:
5
674
by: Don Vaillancourt | last post by:
Hello all, Over the years as I design more database schemas the more I come up with patterns in database design. The more patterns I recognize the more I want to try to design some kind of generic design patterns that can be used and shared amongst many sub-schemas. For example, the grouping of entities. I may have the following tables: employee, product and client. These tables have no direct relationship with each other. But...
0
2250
by: gasturbtec | last post by:
please help im new at access programming and i just got this project dropped in my lap because the old programmer quit. i've been doing ok so far but now i need to add code to an existing database that is used to connect to other databases and generate reports. below is sample code of how the database does the linking i hope i give you enough info to help me but if not let me know and i will give more. Sub txtShipDataFileSub() Dim...
7
2435
by: PC Datasheet | last post by:
Looking for suggestions ---- A database was designed for a national automobile inspection program. In it's simplest form, the database has two tables: TblOwner OwnerID <Year/Make/Model owned by owner, Owner name/address, etc) TblInspection InspectionID
35
4856
by: Terry Jolly | last post by:
Web Solution Goal: Have a global database connection Why: (There will be 30+ tables, represented by 30+ classes) I only want to reference the database connection once. I put the connection string in the web.config. I created a class with a static database connection and the class opens and closes the database.
76
272588
MMcCarthy
by: MMcCarthy | last post by:
Normalisation is the term used to describe how you break a file down into tables to create a database. There are 3 or 4 major steps involved known as 1NF (First Normal Form), 2NF (Second Normal Form), 3NF (Third Normal Form) and BCNF (Boyce-Codd Normal Form). There are others but they are rarely if ever used. A database is said to be Normalised if it is in 3NF (or ideally in BCNF). These steps are descibed as follows: Note: When attribute...
0
5000
bartonc
by: bartonc | last post by:
With one small change to the view/control: self.staticText3 = wx.StaticText(id=wxID_DBCONNECTDIALOGSTATICTEXT3, label='ODBC Data Source Name', name='staticText3', parent=self, pos=wx.Point(240, 40), size=wx.Size(143, 16), style=0) and some rework of the model:##from MySQLdb import * from mx.ODBC.Windows import * from time import time class DBServer: def __init__(self, master):
8
2764
by: situ | last post by:
Hello all, i have Database1 and database2, is it possible to make database connection to database2 by running stored procedure on database1. Thanks and Regards Situ
12
3948
by: grace | last post by:
i am wondering why my database retrieval becomes too slow...we set up a new server (ubuntu, breezy badger) machine where we transferred all our files from the old server.. Our new server uses Asus p5pe-vm motherboard and an Intel Pentium D 3.0Ghz processor, compared to the old one where we uses asrock motherboard and AMD Duron. Both has the same version of mysql installed... To summarized, both machine has the same configuration except...
9
2339
by: Peter Duniho | last post by:
Is there a straightfoward API in .NET that allows for inspection of a database? That is, to look at the structure of the database, without knowing anything in advance about it? For example, retrieving a list of tables in the database. Doing a little browsing in MSDN, I see that the abstract representation of a database appears to be the DataSet class. I also see that I can use "data adapter" classes (e.g. OdbcDataAdapter) to connect a...
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9575
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10564
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10320
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5645
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4288
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.