2

We are using CodeIgniter to wrap some internal functions and to display the results in json.

Occasionally our internal functions might have debug strings printed to the screen. So we have started using output buffering to capture any debug and add this to the result $data['response']['debug'] = $ob;

This seems to have worked pretty well as we have started dropping this code into most our publicly exposed CI functions.

We seem to be repeating this code flow a-lot now.

What would be the best way to extract the 'repeated' sections into a general template that is called when required? (not every function implements this - just most).

Example code:

public function some_function($var){
    ob_start();  //repeated

    $this->load->model('some_model');
    $result = $this->some_model->do_something($var);

    if($result){
        $data['response']['result'] = true;
    }else{
        $data['response']['error'] = 'Something not found.';
    }

    $ob = ob_get_clean(); //repeated

    if($ob!=''){
        $data['response']['debug'] = $ob; //repeated
    }

    $this->load->view('json',$data); //repeated
}
  • Not sure I follow what "We are using CodeIgniter to wrap some internal functions" means, but you may want to look into Controller hooks http://ellislab.com/codeigniter/user-guide/general/hooks.html – jmadsen Aug 21 '13 at 10:54
  • By 'Internal functions' I mean our legacy code (that is normally hidden from public view). We are exposing some of these via json. Perhaps you could expand your answer re hooks a little? – Gareth Foster Aug 23 '13 at 19:46

1 Answers1

0

If you have PHP 5.3.0 or higher, you can do something like this :

function debug_func($code){

ob_start();  //repeated

$code();

$ob = ob_get_clean(); //repeated

if($ob!=''){
    $data['response']['debug'] = $ob; //repeated
}

$this->load->view('json',$data); //repeated

}

and use your code like this :

debug_func(function(){
$this->load->model('some_model');
$result = $this->some_model->do_something($var);

if($result){
    $data['response']['result'] = true;
}else{
    $data['response']['error'] = 'Something not found.';
}

});

and do all your codeing like that.

Ofcourse you can also wrap the repeated code in 2 functions and call them instead, just as annoying but will save you some space.

eric.itzhak
  • 15,752
  • 26
  • 89
  • 142