Welcome Guest, Not a member yet? Register   Sign In
Handle object in class helper - Best practice
#1

(This post was last modified: 11-10-2015, 02:16 AM by sebastianvirlan.)

I made this class for categories:


PHP Code:
class Categories
{

 
   private $_category;
 
   private $_ci;

 
   public function __construct($category){

 
       $this->_ci get_instance();
 
       $this->_ci->load->model('produse_model''produse');
 
       $this->_category $category;
 
   }


 
   public function categories(){

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

 
       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?
Reply
#2

Why not transform it into a library?
Reply
#3

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

Can you tell me the difference?

Advantages?
Reply
#4

(This post was last modified: 11-10-2015, 04:05 AM by sintakonte.)

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
Reply
#5

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

exactly
Reply
#7

(This post was last modified: 11-10-2015, 08:01 AM by sebastianvirlan.)

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.


EDIT
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');
        
$this->db->group_by('a.id_categorie');
        
$result $this->db->get();
        
//echo $this->db->last_query();
        
return $result->result();
    } 
Reply
#8

(This post was last modified: 11-11-2015, 12:50 AM by sebastianvirlan.)

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




Theme © iAndrew 2016 - Forum software by © MyBB