Welcome Guest, Not a member yet? Register   Sign In
Adding functionaly to cotroller
#1

[eluser]Unknown[/eluser]
Hello.

I often use the same block of code for outputing status of execution of my functions in json format. for example:

Code:
$this->output->set_content_type('application/json');
  $this->output->set_output(json_encode(array('status' => 'success')));

1. How can I make a function that will be accessible in each controller? I think I should change something in system folder, but I'm just not sure

2. When I write a function in controller, often I have next logic: if I get wrong get/post data, or maybe user is not logged, etc I send status in json format, something like "status":"error", and then die. But $this->ouput->set_output() works for me only if I put it in the end of functon. I know that I should do any output once in the end, but for example:

Code:
public function myfunc() {
     $this->output->set_content_type('application/json');
     if (!$this->input->get('param')) {
           // here I should send an error, and then die.
           $this->output->set_output(json_encode(array('status' => 'error')));
           die;
           // and that's it. I won't send any data further
     } else {
           // here I do something and then send results
           $this->output->set_output(json_encode($result)));
     }
}

Instead I want to use my own function, like $this->setStatus('error', 3) (3 is error number for example), or maybe $this->output->sendStatus('error', 3) and do it not only in the end, because sometimes it makes functions harder to construct

Thanks in advance
#2

[eluser]CroNiX[/eluser]
Either create a library (where you could have a class with variables and multiple methods) or a helper and autoload it. Then it will be available to all controllers/views/etc. You could also extend the output class and add your own custom methods (extend, not change stock CI input class). All of these ways are covered in the user guide.





Theme © iAndrew 2016 - Forum software by © MyBB