I am going to built the custom library. I want to pass string from view to library and process and then return to same view after. My code looks like:
application/libraries/MultiImageParser.php
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//return profile pic of img arrays.
class MultiImageParser {
function parser($multiImage) { //get $prods->images here as parameter
$images = $multiImage; //gets multiple image from controller like 1.jpg,2.jpg,3.jpg
$pieces = explode(",", $images); //explode make arrays.
$one = $pieces[0];
return $one;
}
}
View
<?php
$CI =& get_instance();
$CI->load->library('multiImageParser'); //loading library from view
$profilepic = $CI->multiImageParser->parser($prods->images);
echo $profilepic;
?>
And I get this error call to member function parser() on a non-object
. How can I resolve this.
The problem is the way you are calling your library method. As per the CI Documentation - Creating Libraries:
So in your case it should be:
However, you should always do all this work in the Controller, not in the View to follow a correct MVC pattern
your controller should be like this:
and your View:
You have got some string that is imploded array of image names glued by comma. Make your job of requested separation of that element (and consequently dedicating it to variable) in controller that loads your view. To explain myself bit better, this code should stay in the controller that is loading view file you posted here. Or in other words, in same controller where is generated
$prods->images
property. Also it doesn't need to be library, it can be (private/protected maybe?) method of same controller. But also, if you want it on different places used, you answered with helper option too.