Welcome Guest, Not a member yet? Register   Sign In
Vars in models
#1

[eluser]fakeempire[/eluser]
I've noticed in other peoples code that I look at that their models always have the variables declared at the begining --
Code:
class Blogmodel extends Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function Blogmodel()
    {
        // Call the Model constructor
        parent::Model();
    }
}
I never do this and don't seem to have an issue-- is there a reason I should be doing that? What do you gain?

Thanks.
#2

[eluser]zwippie[/eluser]
I don't think the class variables are really necessary.

From the same Blogmodel example in the userguide:
Code:
function insert_entry()
    {
        $this->title   = $_POST['title'];
        $this->content = $_POST['content'];
        $this->date    = time();

        $this->db->insert('entries', $this);
    }
Can also be achieved without the class variables:
Code:
function insert_entry()
    {
        $data = new stdClass();
        $data->title   = $_POST['title'];
        $data->content = $_POST['content'];
        $data->date    = time();

        $this->db->insert('entries', $data);
    }
However, more sophisticated ActiveRecord models sometimes make uses of the class variables for each field in the database.
#3

[eluser]xwero[/eluser]
If you want to store data that has to be used by multiple methods you add variables to the beginning of the class. If they are public (all var defined variables are) you can change them form outside the class if you wanted to
Code:
$this->image_lib->width = 200;
// is the same as
$config['width'] = 200;
But with the previous example you don't have the advantage of the checks in the initialize method.

It's powerful stuff if you use it right.
#4

[eluser]Sean Murphy[/eluser]
One benefit of using member variables is that you can set default values and you don't have to check if the variable is set when working with it.
#5

[eluser]tonanbarbarian[/eluser]
class variables, or properties as they are called, can be useful for lots of things
for example I store any validation rules for a model in properties of the model and then retrieve them to set the rules. This allows me to keep all of the information about the model in the most logical place, in the model

I also use it for automation.
I extend the default model and add methods to load, save, delete etc, and having properties that indicate the name of the table and the primary key etc come in useful in this situation.




Theme © iAndrew 2016 - Forum software by © MyBB