PHWinfo banniere

Titres
PORTAIL ANNUAIRE ARTICLES COMPARATEUR HÉBERGEURS DEVIS FORUMS RÉDUCTEUR D'URL
Précédent   PHWinfo > Autres forums > Forum Programmation & Conception > comp.lang.php > Objects or not ?
S'inscrire FAQ Membres Recherche Messages du jour Marquer les forums comme lus
Objects or not ?

Réponse
 
LinkBack Outils de la discussion
Vieux 13/11/2007, 14h23   #1
floortje4@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut 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('SELECT * 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('UPDATE 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=users.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

  Réponse avec citation
Vieux 13/11/2007, 14h27   #2
Jonas Werres
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

> 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.
  Réponse avec citation
Vieux 13/11/2007, 14h40   #3
Jerry Stuckle
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

floortje4@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('SELECT * 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('UPDATE 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=users.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.
jstucklex@attglobal.net
==================

  Réponse avec citation
Vieux 13/11/2007, 15h05   #4
floortje4@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

On 13 nov, 14:40, Jerry Stuckle <jstuck...@attglobal.net> wrote:

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::select('SELECT UserId FROM forum');

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

return $aUserObj;
}


  Réponse avec citation
Vieux 13/11/2007, 15h07   #5
floortje4@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

On 13 nov, 14:27, Jonas Werres <jo...@example.org> wrote:
> > 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 !



  Réponse avec citation
Vieux 13/11/2007, 15h13   #6
Jerry Stuckle
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

floortje4@gmail.com wrote:
> On 13 nov, 14:40, Jerry Stuckle <jstuck...@attglobal.net> wrote:
>
> 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::select('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.
jstucklex@attglobal.net
==================

  Réponse avec citation
Vieux 13/11/2007, 16h04   #7
floortje4@gmail.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

On 13 nov, 15:13, Jerry Stuckle <jstuck...@attglobal.net> wrote:

> >> 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

  Réponse avec citation
Vieux 13/11/2007, 16h41   #8
ZeldorBlat
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

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('SELECT * 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('UPDATE 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=users.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('SELECT * 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('SELECT * FROM forum INNER JOIN USERS on
forum.UserId=users.UserId');
$users = User::fromArray($forumdata);

  Réponse avec citation
Vieux 13/11/2007, 18h46   #9
Jerry Stuckle
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

floortje4@gmail.com wrote:
> On 13 nov, 15:13, Jerry Stuckle <jstuck...@attglobal.net> wrote:
>
>>>> 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.
jstucklex@attglobal.net
==================

  Réponse avec citation
Vieux 13/11/2007, 19h14   #10
Jerry Stuckle
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Objects or not ?

floortje4@gmail.com wrote:
> On 13 nov, 15:13, Jerry Stuckle <jstuck...@attglobal.net> wrote:
>
>>>> 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($userId = null) { // To allow for a new user
$this->userId = $userId;
}

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

function setUserId($userId) {
// 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::select('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->fetchForumUsers();
$users = $userList->fetchUsers();


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

  Réponse avec citation
Réponse


Outils de la discussion

Règles de messages
Vous ne pouvez pas créer de nouvelles discussions
Vous ne pouvez pas envoyer des réponses
Vous ne pouvez pas envoyer des pièces jointes
Vous ne pouvez pas modifier vos messages

Les balises BB sont activées : oui
Les smileys sont activés : oui
La balise [IMG] est activée : oui
Le code HTML peut être employé : non
Trackbacks are oui
Pingbacks are oui
Refbacks are oui


Fuseau horaire GMT +1. Il est actuellement 16h50.


Édité par : vBulletin® version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0 RC5 Tous droits réservés.
Version française #16 par l'association vBulletin francophone
PHWinfo est un site Éducation Sans Frontières ©2000-2008
Ad Management by RedTyger
©Tous droits réservés par les parties respectives
Page generated in 1,15372 seconds with 18 queries