是否可以为数据库表创建类/对象? [英] Is it OK to make a class/object for a database table?

查看:207
本文介绍了是否可以为数据库表创建类/对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个网站制作者,我有一些表,是否可以始终构建一个类并创建一个对象,基于该表?我有一个老师表(ID,USERNAME)和一个基于 giveMark() editMark 等。另一个是学生(ID,NAME)表, getMarks() getMissingHours()等。现在由于学生和教师之间存在N:M关系,我有一个 link_teacher_student (ID,TEACHED_ID,STUDENT_ID) 帮助表。我应该为它创建类/对象吗?

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?

推荐答案

link_teacher_student 表。 这是在RDBMS结构中常见的,但不是在OOP模型中。 / a>在OOP模型中的相同关系将简单地:

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();
}

然后您将使用教师或学生时,初始化该数组的数据。com / eaaCatalog / dataMapper.htmlrel =noData- code>,例如您的 DAO 会查询教师,并且加入学生,然后Mapper会创建学生对象,并在教师中将它们填充到数组中。

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.

你可以做的是make $ students $ teachers into Repositories 并给它们finder查询查找表的方法,例如

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;
    }
}

这篇关于是否可以为数据库表创建类/对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆