473,788 Members | 2,856 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Objects or not ?

Hi,

Im having a discussion with a friend about Objects.

Let say I create a user Object

class User
{
private $_aUserdata;
rivate $_sId;

function __construct($id )
{
$this->_sId=$id;
$this->_aUserdata= db::select('SEL ECT * FROM users WHERE UserId ="'.
$id.'"');
}

public function getName()
{
return $this->_aUserdata['firstnamename'].' '.$this-
>_aUserdata['lastname'];
}

function __destruct()
{
// just for this example
echo 'UPDATING USER';
$db::update('UP DATE users SET' lastsused="NOW( )" WHERE UserId="'.$this-
>_sId.'"' );
}

}

Now i can have easy access to the users

$user=new User(1);
echo $user->getName();

// Arjen
// UPDATING USER

But no script I ever write is this simple.
Lets says that I want to select all forum entries and display the user
name along with the other data

$forumdata=$db: :select('SELECT * FROM forum INNER JOIN USERS on
forum.UserId=us ers.UserId');

Now my userclass is completely useless because I allready have all the
data I need and I dont want to do another xxx select queries to the
user database. However i would still like to use User::getName()
because I might do some fancy calculation there and i dont want to
multpily my code. I now also dont have access to (the complpetely
useless) destructor so I have to update this manually.

How would I go and solve such a problem ?

I could imagine that I could loop through the forumdata and load the
user data into a new user object but is that really a good
solution ?

Arjen

Nov 13 '07 #1
9 1251
I could imagine that I could loop through the forumdata and load the
user data into a new user object but is that really a good
solution ?
Have a look at Propel or Doctrine.
Nov 13 '07 #2
fl*******@gmail .com wrote:
Hi,

Im having a discussion with a friend about Objects.

Let say I create a user Object

class User
{
private $_aUserdata;
rivate $_sId;

function __construct($id )
{
$this->_sId=$id;
$this->_aUserdata= db::select('SEL ECT * FROM users WHERE UserId ="'.
$id.'"');
}

public function getName()
{
return $this->_aUserdata['firstnamename'].' '.$this-
>_aUserdata['lastname'];
}

function __destruct()
{
// just for this example
echo 'UPDATING USER';
$db::update('UP DATE users SET' lastsused="NOW( )" WHERE UserId="'.$this-
>_sId.'"' );
}

}

Now i can have easy access to the users

$user=new User(1);
echo $user->getName();

// Arjen
// UPDATING USER

But no script I ever write is this simple.
Lets says that I want to select all forum entries and display the user
name along with the other data

$forumdata=$db: :select('SELECT * FROM forum INNER JOIN USERS on
forum.UserId=us ers.UserId');

Now my userclass is completely useless because I allready have all the
data I need and I dont want to do another xxx select queries to the
user database. However i would still like to use User::getName()
because I might do some fancy calculation there and i dont want to
multpily my code. I now also dont have access to (the complpetely
useless) destructor so I have to update this manually.

How would I go and solve such a problem ?

I could imagine that I could loop through the forumdata and load the
user data into a new user object but is that really a good
solution ?

Arjen

First of all, don't do the select in your code. Let your objects do it.

In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Nov 13 '07 #3
On 13 nov, 14:40, Jerry Stuckle <jstuck...@attg lobal.netwrote:

Hi Jerry,
First of all, don't do the select in your code. Let your objects do it.
Yup just trying to make the point without producing tons of code :-)
In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.
Maybe I dont understand you but is what im trying to avoid. Lets say
$aData contains 1000 rows with unique UserId's. Then this code would
produce 1001 select queries.

function CreateUserObj()
{
$aData=$db::sel ect('SELECT UserId FROM forum');

foreach ($aData as $val)
{
// executes a new select statement
$aUserObj[$val['UserId']]=new User($val['UserId']);
}

return $aUserObj;
}
Nov 13 '07 #4
On 13 nov, 14:27, Jonas Werres <jo...@example. orgwrote:
I could imagine that I could loop through the forumdata and load the
user data into a new user object but is that really a good
solution ?

Have a look at Propel or Doctrine
Cool !! This looks like a little overkill but the general idea is
really great !!

Thx Jonas !

Nov 13 '07 #5
fl*******@gmail .com wrote:
On 13 nov, 14:40, Jerry Stuckle <jstuck...@attg lobal.netwrote:

Hi Jerry,
>First of all, don't do the select in your code. Let your objects do it.

Yup just trying to make the point without producing tons of code :-)
>In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.

Maybe I dont understand you but is what im trying to avoid. Lets say
$aData contains 1000 rows with unique UserId's. Then this code would
produce 1001 select queries.
But what you should be avoiding is having to worry about stuff like this
in your code. OO programming is all about abstracting the details.
function CreateUserObj()
{
$aData=$db::sel ect('SELECT UserId FROM forum');

foreach ($aData as $val)
{
// executes a new select statement
$aUserObj[$val['UserId']]=new User($val['UserId']);
}

return $aUserObj;
}

No, this is one query, and you retrieve multiple rows from that query.

But if you need 1000 rows, you need to retrieve all 1000 rows somehow.
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Nov 13 '07 #6
On 13 nov, 15:13, Jerry Stuckle <jstuck...@attg lobal.netwrote:
In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.
After re-reading your reply im guessing we are not talking about the
same thing. Im talking about a join of 2 tables: users and
forum(entries). Im not quite sure where the userlist fits in. I have
allready performed the select statement joing the two tables and I
have all the data I need. Ater getting all the data I need I would
like to make use of the handy classes I have created. Are you saying
that I should pass specific data from each row to 2 new objects (class
User and class Forum).

Arjen

Nov 13 '07 #7
On Nov 13, 8:23 am, floort...@gmail .com wrote:
Hi,

Im having a discussion with a friend about Objects.

Let say I create a user Object

class User
{
private $_aUserdata;
rivate $_sId;

function __construct($id )
{
$this->_sId=$id;
$this->_aUserdata= db::select('SEL ECT * FROM users WHERE UserId ="'.
$id.'"');

}

public function getName()
{
return $this->_aUserdata['firstnamename'].' '.$this-
_aUserdata['lastname'];
}

function __destruct()
{
// just for this example
echo 'UPDATING USER';
$db::update('UP DATE users SET' lastsused="NOW( )" WHERE UserId="'.$this-
_sId.'"' );
}
}

Now i can have easy access to the users

$user=new User(1);
echo $user->getName();

// Arjen
// UPDATING USER

But no script I ever write is this simple.
Lets says that I want to select all forum entries and display the user
name along with the other data

$forumdata=$db: :select('SELECT * FROM forum INNER JOIN USERS on
forum.UserId=us ers.UserId');

Now my userclass is completely useless because I allready have all the
data I need and I dont want to do another xxx select queries to the
user database. However i would still like to use User::getName()
because I might do some fancy calculation there and i dont want to
multpily my code. I now also dont have access to (the complpetely
useless) destructor so I have to update this manually.

How would I go and solve such a problem ?

I could imagine that I could loop through the forumdata and load the
user data into a new user object but is that really a good
solution ?

Arjen
There are lot's of different ways to do this. I typically create
static "factory" methods to create the objects rather than call the
constructor directly. For instance, your constructor can look like
this:

//Protected so you have to use the factory methods
protected function __construct($id , array $userData) {
$this->_sId = $id;
$this->_aUserdata = $userData;
}

Now you create a factory method called "fromID" like this:

public static function fromID($id) {
$class = __CLASS__;
$u = new $class($id, db::select('SEL ECT * FROM users WHERE UserId
="'.$id.'"') );
return $u;
}

And you can create a factory method called "fromArray" like this:

public static function fromArray(array $a) {
$class = __CLASS__;

$r = array();
foreach($a as $row)
$r[] = new $class($row['id'], $row);

return $r;
}

So, for a single id you can get your object like this:

$user = User::fromID(42 );

And, if you already have the result of a query in an array, you can
get an array of user objects without re-running your query like this:

$forumdata = $db::select('SE LECT * FROM forum INNER JOIN USERS on
forum.UserId=us ers.UserId');
$users = User::fromArray ($forumdata);

Nov 13 '07 #8
fl*******@gmail .com wrote:
On 13 nov, 15:13, Jerry Stuckle <jstuck...@attg lobal.netwrote:
>>>In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.

After re-reading your reply im guessing we are not talking about the
same thing. Im talking about a join of 2 tables: users and
forum(entries). Im not quite sure where the userlist fits in. I have
allready performed the select statement joing the two tables and I
have all the data I need. Ater getting all the data I need I would
like to make use of the handy classes I have created. Are you saying
that I should pass specific data from each row to 2 new objects (class
User and class Forum).

Arjen

Yes, UserList would be a list of users. It would perform the SQL
operations to fetch the information and then create a new User object
for each user returned.

And if one User could have many Forum entries, the User class should
contain a list of ForumEntry class objects. The UserList object would
handle this, also (in conjunction with the User object).

--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Nov 13 '07 #9
fl*******@gmail .com wrote:
On 13 nov, 15:13, Jerry Stuckle <jstuck...@attg lobal.netwrote:
>>>In this case, create a userlist class and let it perform the select
statement, building a new userobject for each row.

After re-reading your reply im guessing we are not talking about the
same thing. Im talking about a join of 2 tables: users and
forum(entries). Im not quite sure where the userlist fits in. I have
allready performed the select statement joing the two tables and I
have all the data I need. Ater getting all the data I need I would
like to make use of the handy classes I have created. Are you saying
that I should pass specific data from each row to 2 new objects (class
User and class Forum).

Arjen

As an example:

class User {
private $userId;

function __construct($us erId = null) { // To allow for a new user
$this->userId = $userId;
}

function getUserId() {
return $this->userId;
}

function setUserId($user Id) {
// Validate it as necessary
// You can also return true/false depending on if
// validation succeeds or fails
$this->userId = $userId;
}

// ... other functions
}

class UserList {
private $users;

function __construct () { // Initialize the array
$users = array();
}

function fetchForumUsers ($db) {
$userIds=$db::s elect('SELECT UserId FROM forum');
foreach ($userIds as $userId) {
// This does NOT execute a new SELECT statement!
$this->users[]=new User($userId);
}

function fecthUsers() {
return $this->users;
}
// ... other functions
// I often also add first(), last(), next() and prev() functions here
}

$userList = new UserList();
$userList->fetchForumUser s();
$users = $userList->fetchUsers() ;
--
=============== ===
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attgl obal.net
=============== ===

Nov 13 '07 #10

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

Similar topics

2
8255
by: dasod | last post by:
I would like to know if my method to remove list objects is correct in this small test program. It seems to me that there might be a simplier way, but I'm afraid I don't know enough about list iterators and how they are behaving in situations like this. #include <iostream> #include <list> class Test; typedef std::list< Test* > Tlist;
9
1889
by: Aguilar, James | last post by:
Hey guys. A new question: I want to use an STL libarary to hold a bunch of objects I create. Actually, it will hold references to the objects, but that's beside the point, for the most part. Here's the question: I want to be able to change the references (including deleting them). Is there any way to do that besides using pointers rather than references for the STL library? I'd also prefer to avoid using const_cast, if it is indeed...
6
2581
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
3
3035
by: ytrewq | last post by:
Should dynamic ("expando") properties be restricted to native and user-defined objects? Or should host objects - such as references to the browser or a plug-in or to the document and its elements - also allow them? Adding (and removing) object properties dynamically is an acceptable and common practice in JavaScript, and greatly adds to the power and character of the language. Essentially, an object in JavaScript can be considered to...
8
1863
by: Lüpher Cypher | last post by:
Hi, Suppose we have a hierarchical class structure that looks something like this: Object | +-- Main | +-- Object1
161
7885
by: KraftDiner | last post by:
I was under the assumption that everything in python was a refrence... so if I code this: lst = for i in lst: if i==2: i = 4 print lst I though the contents of lst would be modified.. (After reading that
7
8224
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
21
2217
by: George Exarchakos | last post by:
Hi everyone, I'd like your help... Can we have a std::list<BASEwhere BASE be the base class of a class hierarchy? I want to add to this list objects that are inherited from BASE class but not necessarily the same... class base { int x;
27
2568
by: SasQ | last post by:
Hello. I wonder if literal constants are objects, or they're only "naked" values not contained in any object? I have read that literal constants may not to be allocated by the compiler. If the Standard is saying that "object is a region of storage", I deduce from that that literal constants aren't objects because they may not be alocated as regions of storage in the memory.
14
6027
by: Jess | last post by:
Hello, I learned that there are five kinds of static objects, namely 1. global objects 2. object defined in namespace scope 3. object declared static instead classes 4. objects declared static inside functions (i.e. local static objects) 5. objects declared at file scope.
0
9656
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
9498
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
10373
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
10177
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...
1
7519
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6750
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
5403
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...
1
4074
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
2897
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.