Welcome Guest, Not a member yet? Register   Sign In
Autoloading Models PHP 5 Style
#8

[eluser]Chad Fulton[/eluser]
I'll bite on this.

1. I think that there's no reason that we should be encouraging people to never use local Model instances.

I agree that some model instances should be global, like maybe a User model, or a Page model, or whatever, but there are times when it makes more sense to deal with an object temporarily, in which case it doesn't need to be in the global scope and doing so would make that scope unnecessarily messy. That's the whole point of local scoping in PHP, personally I disagree with CodeIgniter's handling of Models, which makes it difficult to get around that.

The "hack" I use is to add an argument to the constructor of the MY_Model class (which all my models descend from) such that if the argument given is FALSE, it doesn't load the parent constructor (and so doesn't add it to the global scope, but, of course, this also means that you have to get any of the CI variables that you want):

Code:
public function __construct($model = true) {
        if($model) {
            parent::__construct();
        }
        else {
            $ci =& get_instance();
            $this->db =& $ci->db;
            // ...
        }
    }

2. Besides polluting the global space with things that should be left in the local space, I feel like there's an awful burden imposed by allowing only a single instance of a model (I know that you can use the second argument in the load function to assign the model instance to a different global variable, but that's only really helpful if you want 2 or 3 instances of a model). I want to be able to make an arbitrary number of model instances and assign them into an array and then manipulate them as a group:

Code:
foreach($objects as $object) {
  if($object->function()) {
    echo $object->property_1;
  }
  else {
    echo $object->property_2;
  }
}

Of course, none of this has to do with autoloading in particular (since it doesn't matter if you do a require('path/to/model') before the $model = new Model; or not), but is relevant to this case.


Messages In This Thread
Autoloading Models PHP 5 Style - by El Forum - 12-29-2009, 05:36 PM
Autoloading Models PHP 5 Style - by El Forum - 12-29-2009, 07:49 PM
Autoloading Models PHP 5 Style - by El Forum - 12-29-2009, 08:52 PM
Autoloading Models PHP 5 Style - by El Forum - 12-29-2009, 08:57 PM
Autoloading Models PHP 5 Style - by El Forum - 12-29-2009, 09:17 PM
Autoloading Models PHP 5 Style - by El Forum - 12-30-2009, 12:42 AM
Autoloading Models PHP 5 Style - by El Forum - 12-30-2009, 03:05 AM
Autoloading Models PHP 5 Style - by El Forum - 12-30-2009, 04:39 PM
Autoloading Models PHP 5 Style - by El Forum - 12-31-2009, 06:27 AM
Autoloading Models PHP 5 Style - by El Forum - 01-01-2010, 09:10 AM
Autoloading Models PHP 5 Style - by El Forum - 01-01-2010, 09:30 AM



Theme © iAndrew 2016 - Forum software by © MyBB