Welcome Guest, Not a member yet? Register   Sign In
Where should I store functions like...?
#1

[eluser]Carmichael[/eluser]
Hi CodeIgniters!

Where should I store functions like this

Code:
function get_username_by_id($id)
    {
        $q = $this->db->select('user_name')->get_where($this->users_table, array('user_id' => $id));
        
        if (!empty($q->row(0)->user_name))
        {
            return $q->row(0)->user_name;
        } else{
            return false;
        }
    }

I use that kind of functions in multiple controllers/views, so should I store that kind of functions in a helper or what?

I think it is more convenient to make such functions than to build big querys with joins.
#2

[eluser]Samus[/eluser]
[quote author="Carmichael" date="1333801297"]Hi CodeIgniters!

Where should I store functions like this

Code:
function get_username_by_id($id)
    {
        $q = $this->db->select('user_name')->get_where($this->users_table, array('user_id' => $id));
        
        if (!empty($q->row(0)->user_name))
        {
            return $q->row(0)->user_name;
        } else{
            return false;
        }
    }

I use that kind of functions in multiple controllers/views, so should I store that kind of functions in a helper or what?

I think it is more convenient to make such functions than to build big querys with joins.[/quote]

I generally store it in a model which contains methods for dealing with users in general.

Also I would have written that code like this:

Code:
function get_username_by_id($id)
    {
        $q = $this->db->get_where($this->users_table, array('user_id' => $id));
        
        if ($q->num_rows() > 0))
        {
            return $q->row();
        } else{
            return false;
        }
    }
This approach allows you to be able to reuse your code in more situations.

Rather than having a method for returning a users username or age or first name.

Create one that returns all the info for the user.

Then in your view/controller you can specify what value you want.

That's how i'd do it anyway.
#3

[eluser]toopay[/eluser]
Put that in your model.




Theme © iAndrew 2016 - Forum software by © MyBB