0

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
johnny
  • 19,272
  • 52
  • 157
  • 259
  • Straight PHP has no clue about what model is, nor what's a view etc. Therefore you need a framework for the context of your question. – N.B. Aug 25 '14 at 15:02
  • I should have said, my MVC framework. – johnny Aug 25 '14 at 15:09
  • 1
    Very related: http://stackoverflow.com/a/24886699/476 - you don't have "a model" per table. Your database schema and your PHP classes do not in any way need to correspond 1:1. – deceze Aug 25 '14 at 15:17

1 Answers1

1

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.

xJoshWalker
  • 457
  • 2
  • 12