phpcodeigniterdesign-patternsfactory

Codeigniter how to use Factory pattern?


How do I use factory classes call in codeigniter. I have been have trying to implement the following as library

class MyClass {

    public $_class = "Factory";

    /*
      ===================================
      On Create
      =================================== */

    public function __construct() {

        $this->_db =& get_instance();

}
    //other methods
}

class Factory {

    private $_db;
    /*
      ===================================
      On Create
      =================================== */

    public function __construct($data, $db) { 
      $this->_db = $db; 
}
//factory methods
}

$obj = new MyClass();
$res = $obj->call_method_MyClass();

than let say I make a loop on retrived data

foreach($res as $Factory){

$Factory->method_factory();
}

but I do not get an instance to the Factory


Solution

  • I just follow the normal library pattern, basically what is described in the User Guide - it works the same way you're hoping:

    class Factory {
      function __construct() {
        $this->CI =& get_instance();
      }
    
      function get_factory_item() {
        return $factory_item;
      }
    }
    

    Then in your controller you can just call it (if it's loaded):

    $this->factory->get_factory_item();
    

    If you need to call a model or any Codeigniter stuff form the library, you would:

    $this->CI->My_model->get_something($parameter);
    

    Then you can return it to the controller. I prefer to use libraries (or factories you could say) to do all my heavy lifting.

    For exmaple, my model will simply return the data object, then my library will check for num_rows() etc and finally return either the result() object or a boolean FALSE to my controller.

    Then my controller can do simple checks like if ($my_object) so it's nice and clean.

    Hope this helps.