Jump to content

Can Data Objects Be Created From Another Class?


DeX

Recommended Posts

I'm not sure if I phrased that question properly but I'll give an example:

I have a User class and I have a Car class. I have users on a website and they own cars. So if I want to get all users from the database, I use the User class to do that fetch and the same if I want to get all cars from the database. My question is when I want to get all cars owned by a specific person. Should I do something this?

$user = new User(123);

$carsOwnedByUser = $user->getCars();

 

Or should I do something like this?

$carsOwnedByUser = \CarNameSpace\getCars(123);

 

In the first one I have a function in the User class to get all of their cars and in the second one I have a function in the Car class that gets cars when you pass in a user ID. Is one more proper than the other? Each one will return an array of Car objects. Thanks a lot.

Link to comment
Share on other sites

If you're going with an OOP model (and that's a completely separate discussion) then you should continue with it.

Typically the Car class will handle any type of search against its data, meaning that there would be a method like Car::getByUser(user id). In addition to that, you can provide a shorthand from the User class to find that - namely, $user->getCars() that obviously can supply the user ID to getByUser automatically.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.