[nycphp-talk] Constructors and
Dell Sala
dell at sala.ca
Wed Oct 18 23:50:59 EDT 2006
I think you've got the right idea. Loading the user data should occur
outside the constructor so you can check for success.
A little off topic:
It looks like your moving towards a DataObject pattern and if you
haven't explored this already it's worth a look. DataObjects
typically have something like a get() method, or a find() method
which is called after the object has been instantiated.
$user = new DataObject('user');
$user->get($userId);
When you instantiate the DataObject, it's just an empty shell. You
either do a get() or find() to load data into the shell, or you
populate it with your own data and then insert it into the db:
$user = new DataObject('user');
$user->setName('John');
$user->setAge(34);
$user->insert();
Here's a good article that covers the basics:
http://www.onlamp.com/pub/a/php/2004/08/05/dataobjects.html
-- Dell
On Oct 18, 2006, at 7:34 PM, Matthew Terenzio wrote:
> Just want to bounce this off the OO gurus:
>
> Say you have a User object and sometimes you want to create existing
> users and other times new users.
>
> So you instantiate the object:
>
> $user = new User($username)
>
> and the object recognizes the user and grabs all the user data from
> the
> DB. . .or
>
> $user = new $User()
>
> and the object creates a new user in the db
>
> but constructors don't return values so there is no way to test that
> the second case in fact succeeded.
>
> So I'm thinking I must create a method like:
>
> public function init() {
> if ( $this->username == NULL) {
> createUser()
> } else {
> //get user data from db with $username
> }
> }
>
> so I can test whether my initilaization is successful.
>
>
> That's fine. Just seems cumbersome to create a new object and ALWAYS
> follow with a given method.
> I thought that's what constructors were for.
>
> And I know they are. What's the preferred methodology here?
>
> Thanks
More information about the talk
mailing list