Welcome Guest, Not a member yet? Register   Sign In
Best Practice to pass data to a Model from a Controller
#1

[eluser]Abishek R Srikaanth[/eluser]
Hi All,

Is there a best practice on passing data to a Model from a Controller?
- Is it good to pass it as parameters for the function?
- Is it good to create Model level variables to pass data to the functions in a Model from a Controller?

Thanks and Regards
Abishek R Srikaanth
#2

[eluser]WanWizard[/eluser]
In general, you should avoid both, for every method, not only for models.

Only pass data to a method using arguments, only use the return value of the method.

If the method produces extra data that you store in class properties, uses getters and setters to interact with them, do not access the properties directly.

If you do what you ask, you will create a tight coupling between the caller and the callee, which will quickly turn into a nightmare if you decide at one point to change the API of your class. If you abstract everything as much as possible, you can change the internals of the class without having to go through your entire application to see if the change impacts the code calling the class...
#3

[eluser]Abishek R Srikaanth[/eluser]
Could you give me an example of what you have detailed above. That might help me understand it much better.

Thanks and Regards
Abishek R Srikaanth
#4

[eluser]WanWizard[/eluser]
I mean, instead of
Code:
// define the class
class Somemodel
{
    public $var = 'blah';
}

// and use it like so
$this->load->model('somemodel');
echo $this->somemodel->var;

Do

Code:
// define the class
class Somemodel
{
    protected $var = 'blah';

    public function get_var()
    {
        return $var;
    }

    public function set_var($var = null)
    {
        $var === NULL or $this->var = $var;
    }
}

// and use it like so
$this->load->model('somemodel');
echo $this->somemodel->set_var('value');
echo $this->somemodel->get_var();

Now you can change the internals of the class, and have get_var/set_var behave differently, without having to change the code that calls these methods.

You can also use the magic __get and __set methods if you need lots of getters and setters, at the expense of a bit of execution speed.




Theme © iAndrew 2016 - Forum software by © MyBB