Is it OK to make a class/object for a database table? [closed]
I'm a sitebuilder, I have some tables, and is it OK to always build a class and create one object of it, based on that table? I have a teacher table (ID, USERNAME) and a class based on it got giveMark()
, editMark()
etc. Another one is student (ID,NAME) table, with getMarks()
, getMissingHours()
etc. Now since there's a N:M relationship between students and teachers, I have a link_teacher_student (ID,TEACHED_ID,STUDENT_ID) table, which rather is a "helper开发者_开发知识库" table. Should I create class/object for it too?
No, you should not have an object for the link_teacher_student
table. This is common thing to do in a RDBMS structure, but not in an OOP model. The same relationsip in an OOP model would be simply:
class Teacher {
protected $students = array();
}
class Student {
protected $teachers = array();
}
You would then use a DataMapper to init that array when fetching a Teacher
or Student
, e.g. your DAO would query for a teacher and join the students and the Mapper would then create Student objects and populate them into that array in teacher.
What you can do though is make $students
or $teachers
into Repositories and give them finder Methods to query the lookup table, e.g.
class Teacher
…
public function __construct($studentsRepository)
{
$this->students = $studentRepository;
}
public function getStudents()
{
return $this->students->findByTeacherId($this->id);
}
}
class StudentRepository
…
public function findByTeacherId($teacherId)
{
foreach ($this->dao->select('SELECT …', $teacherId) as $student) {
$students[] = $this->studentBuilder->build($student);
}
return $students;
}
}
Yes. It's not just OK to do this, it's a great idea to separate your data layer (or model) from the rest of your code.
Doing so means you can write less code to get more done as you don't have to repeat the same code all over the place, and it means you only have to worry about updating one piece of code when you need to change your model in some way.
It depends on how much functionality you need from your code. If your web app is going to demand a lot of features based on different user types I'd create a different model and controller for each. If there isn't much difference in functionality between user types you can just use a single unified class employing a few more methods to differentiate.
I'd also just add teacher_id
column to the student table - you don't need to create a whole new table to map the relation.
精彩评论