Wszystko prawie działa, ale wyskakuje błąd o nadpisaniu klucza.
Kod wygląda tak:
StudentFaktory
$sql = "SELECT * FROM student WHERE student_id= '$id'"; return new Student($data['student_id'], $data['nazwa']); }else{ throw new Exception("Student $id nie istnieje"); } } $sql = "SELECT kurs.kurs_id, kurs.kurs_kod, kurs.nazwa FROM kurs, student_kurs WHERE kurs.kurs_id = student_kurs.kurs_id AND student_kurs.student_id = '$id'"; foreach ($data as $key => $datum){ $objCourse = new Course($datum['kurs_id'], $datum['kurs_kod'], $datum['nazwa']); $col->addItem($objCourse, $objCourse->getCourseCode()); //echo '<pre>';print_r($col);echo '</pre>'; } } }
CourseClass
class Course { private $_id; private $_courseCode; private $_name; public $students; function __construct($id, $courseCode, $name) { $this->_id = $id; $this->_courseCode = $courseCode; $this->_name = $name; //$this->students = new Collection(); //$this->students->setLoadCallback('_loadStudents', $this); } public function getName(){ return $this->_name; } public function getID(){ return $this->_id; } public function getCourseCode(){ return $this->_courseCode; } public function __toString() { return $this->_name; } }
CollectionClass
class Collection implements IteratorAggregate{ private $_onload; private $_isLoaded = false; public function addItem($obj, $key = null){ $this->_checkCallback(); if($key){ throw new Exception("Klucz $key jest już zajęty"); }else{ $this->_members[$key] = $obj; } }else{ $this->_members[] = $obj; } }
Test
$studentID = 1; try{ $objStudent = StudentFactory::getStudent($studentID); }catch (Exception $e){ //print_r($e); } print $objStudent.' '. ($objStudent->courses->exist('INF101') ? ' jest ' : 'nie jest'). ' zapisany na kurs ';
Gdzie może być problem?