Welcome Guest, Not a member yet? Register   Sign In
Call controller function at end of processing
#1

Hi guys!

I'm currently developing an API, using Codeigniter, and have created a custom API controller that al my controllers extend further. What I'd like to do is have a function in the API controller that sends output to the browser (and sets the correct Content-type headers and such). The way I started implementing it, was by using the __destruct function for that, but that feels extremely 'hacky' and actually prevents my from using the $this->output->set_content_type function.

Now I've looked into hooks, but I'm not sure how I can call a method on the actual controller object. One way I could think of, is by writing a seperate function that fetches a reference to the current controller object and executes the method on that, but it feels like this is not the elegant solution I'm use to from Codeigniter.

Long story short: I have a controller base class (API_Controller) that has a method 'send_output' and is extended by every controller in the API. The 'send_output' method needs to be called whenever processing of the controller object is done.

I hope I've made it sufficiently clear, please let me know if you need more info.
Reply
#2

Why don't you use a helper function for this?

PHP Code:
function api_output($array$type 'json') {
 
   
    
// Set some default headers 
 
   header('Cache-Control: no-cache, must-revalidate');
 
   header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

 
   switch ($type) {

 
       case 'json':
 
           
            
// Convert the array to the correct data type
 
           $data json_encode($array); 

 
           // Set specific header           
 
           header('Content-type: application/json');
 
           
            
// echo the data
 
           echo $data;
 
           break;

 
       case 'xml':

 
           // Convert the array to the correct data type
 
           $data array_to_xml($array);

 
           // Set specific header   
 
           header('Content-type: text/xml');

 
           // echo the data
 
           echo $data;
 
           break;

 
       default:
 
           // Some basic error handeling
 
           header('Content-type: text/plain');
 
           echo 'Unsupported output type';
 
           break;
 
   }

Reply
#3

Thanks for your reply!

That's a feasible way of doing it, but it still feels like I'm missing a more elegant way. CodeIgniter is so packed with functionality, I can't imagine there isn't a way to invoke a method on the main controller after it has finished executing and without having to actually call the method from the child controller class.
Reply
#4

You can create a hook tunction that is executed after your controllers are finished. You should take a look at the docs:

https://www.codeigniter.com/user_guide/g...hooks.html
Reply




Theme © iAndrew 2016 - Forum software by © MyBB