I am using CodeIgniter and have extended CI_Model. so all my models now extend MY_Model.
This works fine.
Issue is that all my models have a secondary associated object. basically a class that gets passed data from the model (usually from the database) and represents that row in the database.
so something like
class Product_Model extends MY_Model{
public function get($id){
//....
return new Product($query->row());
}
}
class Product{
public function __construct(stdClass $data){
//....
self::$ci =& get_instance();
self::$model = self::$ci->products;
}
}
Now I load the Product_Model with an alias $this->load->model('product_model', 'products');
Hence having self::$model = self::$ci->products;
But now I want to have a basic class that all the classes like Product will extend.
I want this to contain the logic to update self::$model.
But I need to know the models alias.
Something like
self::$model = self::$ci->{instantiator_variable_name($this)} which would be self::$model = self::$ci->products
Now obviously that function does not exist but it shows what I want to do.
I know I could for everywhere that I create the Product or similar have
$row = $query->row();
$row->model = $this->ci->products;
return new Product($row);
But I would rather automate it if I could.
It might help if you clarify the situation a bit. Post a bit more of your code please?
For example, Modals (in CodeIgniter) are generally used as singleton classes which (almost) explains using ‘self::” but it looks like you want Product to be an Object. So why does that use
instead of
The fact that you’re aliasing the products model makes me think you might be doing this on purpose (which is why I’m confused, why would you do this?). I think you should review the difference between “self::”, “static::”, and “$this->”. Take a look at http://php.net/manual/en/language.oop5.late-static-bindings.php
rockstarz is correct, you need to use the Factory Pattern. Consider something like this:
Then your model can just use it like
Relevant reading materials:
http://en.wikipedia.org/wiki/Inversion_of_control#Implementation_techniques
http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Dependency_injection