• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Model best practices

#11
[eluser]sqwk[/eluser]
$var would be the name of the property, which in my case is the same as the column in the DB.

#12
[eluser]Eric Barnes[/eluser]
[quote author="sqwk" date="1310540466"]The array is not the problem. foreach handles objects as well. Nothing is getting overwritten, it is just looping though.
Ignore the explicit setters… simplified example.

Code:
class A_Model extends CI_Model {

    private $var1;
    private $var2;

    public function __construct() {
        parent::__construct();
    }

    public function set_var1($var1) {
        $this->var1 = $var1;
        return $this;
    }
    public function set_var2($var2) {
        $this->var2 = $var2;
        return $this;
    }

    public function create() {
        foreach ($this as $var => $value)
            $this->db->set($var, $value);
        $this->db->insert('table');
        // Should really check if everything went OK, but hey…
    }

}

// Controller
$this->load->model('a_model');
$this->users_model->set_var1('foo')->set_var2('bar')->create();
[/quote]

Yes but I am willing to bet (and could be wrong) if you var_dump($this) before your foreach you will see you are actually looping over tons of data. Not just your two vars in this example.

#13
[eluser]sqwk[/eluser]
@eric: That's what I thought and is the reason why I posted this. Thought someone would find some speed problems etc. Just tested it though and I only get the actual properties that are defined in the model.

#14
[eluser]Eric Barnes[/eluser]
[quote author="sqwk" date="1310542513"]@eric: That's what I thought and is the reason why I posted this. Thought someone would find some speed problems etc. Just tested it though and I only get the actual properties that are defined in the model.[/quote]

I did say I could be wrong and didn't have time to actually test that theory on my own. Tongue

#15
[eluser]Jaketoolson[/eluser]
why not overloading with __set?

http://www.php.net/manual/en/language.oo...ng.members

#16
[eluser]sqwk[/eluser]
Used __call to build implicit setter functions that I can override.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.