adnan kamili adnan kamili - 1 year ago 271
PHP Question

Calling model function in view codeigniter

I am new to MVC, I am porting a project written in non-MVC style to MVC, but I am stuck on a problem where it is necessary to call Model function in View.


Table1 - Products:

etc. and for each product there can be multiple versions.

Table2 - Versions:

, ... ,

Now in the View I am displaying products and under each product heading I have to display version list of that product, in non-MVC style it was pretty simple, I can use the following code snippet in View:

foreach ($product as $row)
echo $row['product_name'];
if ($main->getVersionList($vresult,$row["product_id"]))
foreach ($vresult as $vrow)
echo $vrow['version_name'];

Now, I can pass Product array from controller to view but what about each Version array which needs to be generated corresponding to each product?


This is my final working solution (used a map), in controller:

$this->load->model ( 'product_mod' );
$data ['products'] = $this->product_mod->getProductList ();
$data ['versions'] = array ();
foreach ( $data ['products'] as $product )
$data ['versions'] [$product['product_id']] = $this->product_mod->getVersionList ( $product['product_id'] );

Answer Source

MVC or not to MVC

The first thing I should note is that It is impossible to write classical MVC in PHP. In fact the MVC-like PHP frameworks such as CodeIgniter or Yii implements sort of MVP in which:

  • view is passive and unaware of model
  • presenter (controller) changes state of model, reads information and passes it to view

Credits to tereŇ°ko

CodeIgniter Approach

However, particularly in CodeIgniter, you have 3 steps:

  • Create a Model to query through the database and return the data (as an array or object)
  • Create a Controller to load and fetch the result from the Model (a method of the Model), and pass the returned data to the view
  • Create a View and use PHP loops to echo the result out, build the HTML.

Getting all together

Considering the above approach, you need to fetch the result from the database in your Model:


class Product extends CI_Model
    public function get_product($product_id)
        $this->db->where('product_id', $product_id);
        $this->db->join('versions', 'versions.product_id = products.product_id');
        return $query->first_row('array');

Then fetch and pass the result within the Controller:


class Products extends CI_Controller
    public function view($product_id)
        // Fetch the result from the database
        $data['product'] = $this->product->get_product($product_id);
        // Pass the result to the view
        $this->load->view('product_view', $data);

Finally, use the returned data in the view, to generate the list:


// Use $product to display the product.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download