Search code examples
phpcodeignitermodel-view-controllerprojectdirectory-structure

Separating model folder, view folder and controller folder in CodeIgniter


Can I place the model and view folders of the MVC structure of CodeIgniter to different locations irrespective to the regular path?

Move:

application/views
application/models

to some other location, let's say:

abc/views
pqr/models

outside the project folder? If possible, how can I achieve it?


Solution

  • There's no feature to customize the models and views path in CodeIgniter current stable versions (while in CI 3.x you can change the view path as well as application and system).

    But you can load your files outside of the typical views and models folders.

    The path to the file is relative. So you can use ../ to go one UP level in path.

    For example, If the abc folder is placed near application, you should use ../../abc to reach to that folder.

    Take a look at the example below:

    Model:

    class Model_name extends CI_Model {
    
        public function baz($value='')
        {
            return $value;
        }
    
    }
    

    Controller:

    class Foo extends CI_Controller {
    
        public function bar()
        {
            $this->load->model('../../pqr/models/model_name');
    
            $data['var'] = $this->model_name->baz('Yes It Works!');
    
            $this->load->view('../../abc/views/view_name', $data);
        }
    
    }
    

    View:

    <?php echo $var; ?>
    

    Here is the sample folder structure:

    application
    system
    pqr
       /models
              /model_name.php
    abc
       /views
             /view_name.php
    

    As a Side-note: Make sure direct accessing to the pqr or abc directories is restricted. add a .htaccess file inside them with the content of Deny from all.