CakePHP:放置此功能的位置

时间:2012-02-22 20:09:15

标签: cakephp

我有3个模特:学生,课程和学生课程。课程' hasAndBelongsToMany'学生,学生&很多人有很多'课程,和StudentCourse'属于'学生和课程。在学生注册课程之前,我需要检查一些事情(即:课程是否已满,该学生过去是否参加了该课程等)。我可以处理函数内部的逻辑,但是我应该在哪个模型下放置该函数?而且,它应该怎么称呼?我想到的一种方式是:

// Student Model
public function canSignupForCourse($studentId, $courseId) {
    // is the course full?
    // have they signed up before, etc
    // return either true or false
}

// Could it then be called anywhere as:
if($this->Student->canSignupForCourse($studentId, $courseId)) {
    // etc
}

或者,是否有更好/更简单的方法(并且,我是否需要每次都发送studentid和courseid)?

2 个答案:

答案 0 :(得分:2)

我认为最好的办法是尝试将这些限制作为模型中的验证规则来实现。

根据您的描述,通过创建新的StudentCourse来完成申请课程的学生,这样您应该尝试符合验证规则,例如:

// StudentCourse.php

$validate = array(
    'course_id' => array(
         'rule' => array('maxStudents', 30),
         'required' => true,
         'on' => 'create'
    )
)

function maxStudents($check, $max) {
    $count = $this->find('count', array(
        'conditions' => array('course_id' => $check['course_id']),
        'contain' => false
    ));
    return $count < $max;
}

答案 1 :(得分:0)

我先在这里查看手册中的示例:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model

这应该说服你,你可能也应该让学生'hasAndBelongsToMany'课程(因为课程has学生,但学生在你的模特关系中没有belongto课程)

然后,您可以将该关系模型定义为CourseMembership(如上面的示例链接中所示)

然后我将canSignupForCourse函数放在该模型中。但是我可能会把这个函数分成几个单独的函数,比如courseNotFull和courseNotTakenBefore

然后我会将这些函数放入模型的验证对象中,如下所示:

public $validate = array( 
    'course_id' => array(
        'courseNotFull' => array( 
            'rule' => array('courseNotFull'), 
            'message' => "Course is full", 
        ), 
        'courseNotTakenBefore' => array(
           'rule' => array('courseNotTakenBefore'), 
            'message' => "Student has taken course before", 
        )
    )
); 

定义模型函数如下:

function courseNotFull() {
    $this->Course->id = $this->data[$this->alias]['course_id'];
    $course = $this->Course->read();

    return $course['Course']['isFull'];
}

function courseTakenBefore() {
    $this->Student->id = $this->data[$this->alias]['student_id'];
    $this->Course->id = $this->data[$this->alias]['course_id'];

    $course = $this->Student->Course->findById($this->Course->id);

    return $course;
}

现在,每当您尝试保存或验证()CourseMembership时,如果验证不成功,验证将返回描述性错误消息。

相关问题