简体   繁体   中英

PHP OOP question

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

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() .

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM