• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handle object in class helper - Best practice

I made this class for categories:

PHP Code:
class Categories

   private $_category;
   private $_ci;

   public function __construct($category){

       $this->_ci get_instance();
       $this->_category $category;

   public function categories(){

       foreach($this->_category as $categorie):
           $categorie->numar_produse $this->_ci->produse->count_by_category_id($categorie->id_categorie);

       return $this->_category;

   public function category(){

       return $this->_category->numar_produse $this->_ci->produse->count_by_category_id($this->_category->id_categorie);

Then in controller:

PHP Code:
$categories         = new Categories($this->categorii->entries());
$data["categories"] = $categories->categories(); 

So in my class I get the number of the items for each category.

[Image: dGJiFby.png]

Is this the best practice?

Why not transform it into a library?

(11-10-2015, 03:48 AM)Avenirer Wrote: Why not transform it into a library?

Can you tell me the difference?


i'm not so sure about your way of doing things
i think in general you should avoid calling models within your objects because objects needs to get filled by a model
and the model should return the prepared objects to the controller

a Library can do that but in this case i think a library is a wrong approach - you need a category wrapper object or something like this

Like you told me in this post http://forum.codeigniter.com/thread-63496.html ?


I was thinking, wouldn't be more practice if I join the categories table with products and count the products? And no more foreach and count method needed.

This was the best solution:

PHP Code:
function entries() {
$this->db->select('a.nume_categorie, a.slug_categorie, COUNT(a.id_categorie) as numar_produse');
$this->db->from($this->_table.' a');
$this->db->join('produse b''a.id_categorie = b.id_categorie');
$result $this->db->get();
//echo $this->db->last_query();
return $result->result();

Or I can use query cache, and on every ADD/DELETE delete cache and rebuild.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

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