passing parameter from view to library and return

2019-08-17 17:52发布

问题:

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.

回答1:

The problem is the way you are calling your library method. As per the CI Documentation - Creating Libraries:

Object instances will always be lower case

$this->someclass->some_function();  // Object instances will always be lower case

So in your case it should be:

$profilepic = $this->multiimageparser->parser();

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:

 public function controller_method() {
    $this->load->library('MultiImageParser');
    $img = $this->multiimageparser->parser();
    $data = array(
        "profilepic" => $img
    );
    $this->load->view('view_name', $data);
}

and your View:

echo $profilepic;


回答2:

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.