php - CodeIgniter - Code repetition and passing variables to functions -
i have following code in controller:
<?php class student extends ci_controller { function index() { $data = $this->init->set(); $this->parser->parse('include/header', $data); $this->parser->parse('student/student_index', $data); $this->parser->parse('include/footer', $data); } function planner() { $data = $this->init->set(); $this->parser->parse('include/header', $data); $this->parser->parse('student/student_cal', $data); $this->parser->parse('include/footer', $data); } } ?> as can see, there's lot of repetition here. of it. put variables in model have call model function each time instead of putting whole $data array @ start of each function. anyway, tried reduce repetition here doing following:
<?php class student extends ci_controller { function index() { $data = $this->init->set(); $this->parser->parse('include/header', $data); switch($this->uri->segment(2)) { case '': $this->home($data); break; case 'planner': $this->planner($data); break; } $this->parser->parse('include/footer', $data); } function home($data) { $this->parser->parse('student/student_index', $data); } function planner($data) { $this->parser->parse('student/student_cal', $data); } } ?> this, somehow, works fine homepage. parses variables , there's no problem whatsoever. however, on 'planner' page, errors:
message: missing argument 1 student::planner()
message: undefined variable: data
message: invalid argument supplied foreach()
i'm quite sure these errors because function somehow doesn't receive $data array. read in ci docs third segment in url gets passed argument, , in case third segment non-existent, nothing gets passed. however, ci docs didn't tell me how pass $data array index() function planner() function. wonder why home function works fine, without errors.
now, don't see reason refactoring if it's going make code hard at. i'm not entirely sure parse function does, way changed pass parameter string, preferably i'd load content buffer , pass in way. here's cleaner , readable removable of duplication... , works :).
class student extends ci_controller { private function load_student_page($content){ $data = $this->init->set(); $this->parser->parse('include/header', $data); $this->parser->parse($content, $data); $this->parser->parse('include/footer', $data); } function index() { $this->load_student_page('student/student_index'); } function planner() { $this->load_student_page('student/student_cal'); } }
Comments
Post a Comment