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.
Scenario:
Table1 - Products:
contains product_id
, product_name
etc. and for each product there can be multiple versions.
Table2 - Versions:
contains version_id
, version_name
, ... , product_id
etc.
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?
Update:
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'] );
}
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:
Credits to tereško
CodeIgniter Approach
However, particularly in CodeIgniter, you have 3 steps:
Getting all together
Considering the above approach, you need to fetch the result from the database in your Model:
application/models/product.php
Then fetch and pass the result within the Controller:
application/controllers/products.php
Finally, use the returned data in the view, to generate the list:
application/views/product_view.php
You should do mysql query in your model, for example products_model (don't forget to load it)
Example Query : This is just select * from products
So as I see , you are foreach guy like me, rather than using mass queries.
In your controller you could load $products my your model.
My solution is creating a new array then putting new values in it.Also you need to getVersionList function in your model.
So add your new array to $data you could have them in your view file.
Sorry I didnt figure out all your queries but I think its better to teach how to catch fish than giving a fish.