Welcome Guest, Not a member yet? Register   Sign In
Where should $this->input->post be in model or controller?
#1

[eluser]cleansugar[/eluser]
option 1:
model:
Code:
function simpan() {
         $data = array(
             'kode_barang'=>$this->input->post('kd_brg'),
            'nama'=>$this->input->post('nm_brg'),
            'satuan'=>$this->input->post('satuan'),
            'harga'=>$this->input->post('harga'),
            'stok'=>$this->input->post('stok')
        );
    
        $this->db->insert('barang', $data);

option 2:
controller:
Code:
function submit(){
$data = array(
    $name => $this->input->post('name'),
    $sex => $this->input->post('sex'),
};
$this->hello_model->insertData($data)

model:
Code:
function inserData() {
        $this->db->insert('barang', $data);
}

If I want to pass POST data to DB, at option1, $this->input->post is in model and at option 2, $this->input->post is in controller.

Which is right in MVC pattern?
#2

[eluser]naren_nag[/eluser]
Classic MVC pattern -- variable names in the model map to fields in the table where we validate

Model:

Code:
class Product extends Model {

var $id;
var $name;

function __contruct() {

  parent::__construct();

}

function save() {

  if(isset($this->name))
     $data["name"] = $this->name;
  else
     return FALSE;

  if($this->id > 0)
    update
  else
    insert

  return TRUE;

} // end function

} // end model

Controller -- we get our values from our view, validate them, and then call our model

Code:
.. snip ..

$this->load->model('product', 'productModel');

$productModel->id = $this->input->post("id");  // let's assume this is a hidden input field
$productModel->name = $this->input->post("name", TRUE); // and this is a text field

if(! $productModel->save())
  show_error("Failed to save");

.. snip ..


Also, there is no one way -- take a look at CI's inbuilt form validation class. That's a pretty good pattern to follow.

cheers,

naren
#3

[eluser]Rick Jolly[/eluser]
Option #2.

Generally, you want to decrease hard-coded dependencies within your code. Say, for example, you decided to allow model variables to be set using input other than $_POST. With option #1, you'd have to change your model class.

Normally, where possible, we should pass dependencies into our classes. This is known as Dependency Injection.




Theme © iAndrew 2016 - Forum software by © MyBB