tags:

views:

136

answers:

5
+3  Q: 

PHP OOP question

Hi all,

i was just looking for a bit of advice, currently my DB design is that one user has many blog postings. Now i have a user class and a blog class.

However im not sure about the proper way to get all blog posts for that user. Do i create a getAllBlogs() function in the user class which returns blog objects or do i create a main blog class that you can search by user, so it'd be getAllBlogsForUser($id)

Thanks :-)

+6  A: 

I'd personally use the later option. This is because the blog class knows how to deal with the blog table(s). I wouldn't want to write blog-specific DB code in the user class. On the other hand, you still can add User::getAllBlogs() as a wrapper around Blog::getAllBlogsForUser().

Lukáš Lalinský
Exactly. A static method in Blog, which can be called by an instance method in User is probably the way to go. Adding the method to user gets you convenience, and caching (see my answer, below)
timdev
+2  A: 

It's really up to you. Since users are pretty tightly coupled to blogs, you could do both.

Consider how nicely they could play together:

<?PHP
class User {
    protected $_blogs;

    public function getBlogs($force=false){
        if (empty($this->_blogs) || $force){
            $this->_blogs = BlogClass::getBlogsByUser($this->user_id);
        }
        return $this->_blogs;
    }
}

Now you can grab a user's blogs whenever you want, and it will fetch them only when necessary. The $force parameter can be used to force a reload.

timdev
+1 extra effort for implementing caching
Tres
A: 

I'd use both, like User::getPosts and Posts::findByUserId ("Posts" as model name sounds better to me than "Blogs" ). Both methods have similar functionality and which one to use depends on the context, for example, frontend will rather use Users model, while in admin interface 'finder' methods could be more appropriate.

stereofrog
A: 

I would create both. Your User::getBlogs() could use Blogs::getBlogsByUserId($idUser) since when you are in the user context, you will have access to the user's id to pass to the Blogs method.

Tres
+1  A: 

i am not sure if this is actually a helpful answer .. however if your db design is done correctly with the correct normalization practices in place .. it should be indicative of your class layouts as well. as User is an independent entity, and posts use user_id or something as the foreign key , it should clearly give you the idea who should be the master. Users can exist with-out posts , however posts can not exist with out users. So it makes sense to put the get posts method in the postings class rather than the users class.

Sabeen Malik