dousui6488 2014-08-25 14:40 采纳率: 100%
浏览 45

如何使用PHP在MVC中呈现Master Detail数据?

I can't find an answer to this anywhere. I've seen code examples in C# with ASP.NET MVC, but nothing in PHP outside of a CMS or framework.

If I have two tables, students and classes, how do I get that data rendered in the view?

If I query two different tables in one model (same function/method, however), does that somehow violate the principles of MVC? What about 20 different tables? That sounds like a lot of overhead for nothing a one off table you might only query once or twice. Do I really need 20 models?

Can someone please show me this in straight PHP with no frameworks and no CMS?

EDIT: This is for building my own MVC, so "straight" PHP means me building this component.

  • 写回答

1条回答 默认 最新

  • dpndp64206 2014-08-25 15:56
    关注

    My approach would probably be to use a repository for classes and users in this case.

    StudentRepository

    Retrieves instances of students class based on some criteria. This might have a method called getStudentsByClass($classID) that would retrieve the students for a class by it's class id.

    SchoolClassRepository

    Retrieves instances of a school class based on some criteria. For instance, classes for a semester.

    getClassesBySemester($semesterID)

    Then in your regular "SchoolClass" class, I would have a function that uses the StudentRepository to retrieve classes for the current class. For instance:

    <?php 
    class SchoolClass(){
        private $id;
        private $students;
    
        public function getStudents(){
            $repo = new StudentRepository();
            return $repo->getStudentsByClass($this->id);
        }
    }
    
    ?>
    

    This would mean that your queries to find students for a class would not be exposed in your SchoolClass model. The only thing that the SchoolClass knows about is that the StudentRepository returns the users that it needs.

    You would then pass a SchoolClass model as your data model to grab information in your view.

    评论

报告相同问题?