Will Ashworth
Will Ashworth

Reputation: 1088

Access data from callback function at the class level in a controller in CodeIgniter

I have a callback function that I'm using to validate a submitted video URL based on YouTube or Vimeo APIs (depending on which URL they submitted). The callback function, as part of the validation, checks to validate their submission based on information we receive back from the video site's API.

All code functions 100% correctly and I have proper status' returned to the form validation, but the rest of the data we received from the YT or Vimeo API I would like to use higher up the chain in CodeIgniter. The problem is that this data is not accessible in the class, which I would then typically throw to the view.

Is there any way to get arrays or data set in a callback function accessible at the class level in my controller (where the validation happens)? I've been driving myself bonkers trying to figure this out with no success.

Upvotes: 0

Views: 256

Answers (1)

minboost
minboost

Reputation: 2563

You can put the validation (and other API calls) in a library object that stores the response. Let's assume this library class is named YouTubeAPI, the response is stored in a member named 'response', and the file is located in /libraries/youtube/YouTubeAPI.php.

The validation function in your controller can load this into CI using the load function in the controller.

$this->load->library('youtube/YouTubeAPI');

This makes it available in any controller or view using

$r = $this->youtubeapi->response; // assign to arbitrary local variable

Or available in any library using

$CI &= get_instance();
$r = $CI->youtubeapi->response; // assign to arbitrary local variable

When using custom validation callbacks, I typically use the callback function as a wrapper to a library or helper that does the actual validation. This keeps it DRY in case you have to validate in multiple places.

Upvotes: 2

Related Questions