Question

Let say we have the following MVC architecture in CI

models/my_model.php
views/my_view.php
controllers/my_controller.php

and inside my_model.php I have 3 methods

my_model->method1()
my_model->method2()
my_model->method3()

and inside my_controller.php I have 3 methods

 my_controller->method1()
 my_controller->method2()
 my_controller->method3()

each controller method calls its corresponding model method like this

//my_controller.php
    public function method1()
    {
    $record_id = 1
    $this->load->model('my_model1');   //load the model file
    $data['result'] = $this->my_model1->method1($record_id); // call the method method1 inside the class my_model1
    $this->load->view('my_view',$data);
    }

the question is: "is there any good practice of having less classes and many methods inside those classes or is it better to create new files (or classes) for each method" like so:

models/my_model.php
models/my_mode2.php
models/my_mode3.php
views/my_view.php
controllers/my_controller1.php
controllers/my_controller2.php
controllers/my_controller3.php

what are your thoughts

thanks

Was it helpful?

Solution

Good coding practice is to re-use code. Classes and Objects (OOP in general makes this easier).

If you have 3 classes all with the same functions (That is not the constructor) doing the same thing, you might want to look at your Class structure. That function should then be implemented in a Parent class or in a static collection of functions.

If you have 3 functions doing 3 different things, it's a different story. Less code is always good. See Link:

http://www.folklore.org/StoryView.py?project=Macintosh&story=Negative_2000_Lines_Of_Code.txt

And further more, these general coding practices apply to every class, be it Controller or Model. If you're using OOP, you should be re-using your code (re-use, re-fuse, recycle... yes? no? whatever), I don't think I need to explain the benefit of re-using your code, (Things like debugging, editing, changing the flow of a function/method, keeping your code simple and clean, all becomes easier.. my bad).

The simplest things are the most beautiful...

... in code at least anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top