2

Quick question about CI.

I have a view with a form, several text input fields and a file upload. I want to be able to take the input from the text fields, save it to the DB, and then upload the image.

I've achieved this by having the upload code in a controller, and if the upload is successful, a call to my Model is made to update the database.

Is this "best practice", or indeed an acceptable way of doing it? Or should the File Upload go in the Model. Does it matter?

Essentially my code is:

 function edit_category() { $config['upload_path'] = 'images/category/'; $config['allowed_types'] = 'gif|jpg|jpeg|png'; $config['max_size'] = '1000'; $config['max_width'] = '300'; $config['max_height'] = '300'; $this->load->library('upload', $config); if(!$this->upload->do_upload()) { $this->session->set_flashdata('status', $this->upload->display_errors()); redirect('admin/category/edit/'.$this->input->post('catID'), 'location'); } else /*no errors, upload is successful..*/ { $fInfo = $this->upload->data(); //$this->_createThumbnail($fInfo['file_name']); //process form POST data. $data = array( 'catName' => $this->input->post('catName'), 'catDesc' => $this->input->post('catDesc'), 'catImage' => $fInfo['file_name'] ); /* update the database */ $category = $this->category_model->edit_category($data, $this->input->post('catID')); 

3 Answers 3

5

I would put this in a model because I like to keep my controllers as slim as possible. I think of the controller as the link between the views and the back-room processing, not the processing itself. I'm not sure if this is "best practise" or not. It will certainly work the way you're doing it too. CodeIgniter allows you to be quite flexible in how you apply mvc theory.

Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to ask a question. How can I return the upload error, or the upload data from the model back to the controller, in order to display them into the view? Is there another way to do it without using flashdata?
0

Use your models to interact with data whether it's a database interaction, an api call, or a file upload and download. Use your controller to run the show and make calls to that data. Do your best to keep them all separate in case the method for interacting with that data ever changes. Most of the time we think of the model as a database function, but it really should be ANY data no matter how it's retrieved.

Comments

-1

I came out with this same dilemma, should I put the file upload functionality in controller or model. After few trial and error I decided to put it under model for reusable purposes as calling controller from another controller is against the MVC concept.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.