Jump to content

Function per field or select all data


Adamhumbug
Go to solution Solved by Barand,

Recommended Posts

Hi All,

I am building an application that has users.

My questions is, when showing the user information, would it be better to have a seperate function for every item that i want to retrieve (first name, last name, email address) or should i just have a function that builds the whole data set and gets all the fields that i need in one go.

I am thinking about not duplicating my work as i will need to get the users name in other places and will need to get their email in other places.

Is it is a good idea to have a function to get each piece of data one by one or is this overkill?  I will need 10 functions to run and 10 database connections just to show basic user info.

Link to comment
Share on other sites

:psychic:

You're asking for advice about a specific implementation of something that I, and presumably many others here, have no idea about. What "function"? What "data set"? What "fields"? What is it that you're worried about "duplicating"?

Then you say something about needing multiple database connections, which makes me worry...

Link to comment
Share on other sites

So i have a user form that collects:

First Name
Last Name
Email
Dietry Requirements
Gender
X
Y
Z

 

When pulling up this user information i could create one function

getAllUserData()

that gets all the user data from the DB and builds the display.

But later i will need to get the users name - which would be its own function or maybe the email address that would be its own function.

The question is, if i know that i am going to have a function that pulls the users name and a function that pulls the users email address, do i bother with a function that pulls all the user data in one - or would just pulling individual fields in their own function be a better option.

The database connection comment was more about each function having to establish a connection and send a query to the database - it could be 10 or more queries to get all of the data that i need for the user rather than just one.

I am just trying to weigh up benefits of each approach and wondered what may be concidered standard.  I have always pulled all the data that i need in one function and if there is a case where i need slightly different data, i just make another function.

Link to comment
Share on other sites

So i could have a set of functions that get a single piece of data:

getFirstName($id)
getLastName($id)
getEmail($id)
getDietary($id)
getX($id)

and a function that calls these singles and builds the view:

getUserInfo($id){

getFirstName($id)
getLastName($id)
getEmail($id)
getDietary($id)
getX($id)

}

 

or i could just getAllUserData()

and just send one query to the database.

Link to comment
Share on other sites

  • Solution

Whichever approach you use, do NOT connect to the database inside every function. Connect once to the db at start of each script and pass the connection to the functions. (The connection is the slowest part of the process)

So the function calls are

getFirstName($pdo, $id)
getLastName($pdo, $id)
getEmail($pdo, $id)
getDietary($pdo, $id)
getX($pdo, $id)

I'd go with a single function


$user = getUserData($pdo, $user_id);                              // get an array containing the user data
if ($user) {
    $fullname = $user['firstname'] . ' ' . $user['lastname'];     // use array elements as required
}

function getUserData($pdo, $id)
{
    $res = $pdo->prepare("SELECT firstname
                               , lastname
                               , email
                               , diet
                               , gender
                               , x
                               , y
                               , z
                          FROM user
                          WHERE id = ?      
                          ");
    $res->execute([$id]);
    return $res->fetch();
}

 

Link to comment
Share on other sites

25 minutes ago, Barand said:

Whichever approach you use, do NOT connect to the database inside every function. Connect once to the db at start of each script and pass the connection to the functions. (The connection is the slowest part of the process)

So the function calls are

getFirstName($pdo, $id)
getLastName($pdo, $id)
getEmail($pdo, $id)
getDietary($pdo, $id)
getX($pdo, $id)

I'd go with a single function


$user = getUserData($pdo, $user_id);                              // get an array containing the user data
if ($user) {
    $fullname = $user['firstname'] . ' ' . $user['lastname'];     // use array elements as required
}

function getUserData($pdo, $id)
{
    $res = $pdo->prepare("SELECT firstname
                               , lastname
                               , email
                               , diet
                               , gender
                               , x
                               , y
                               , z
                          FROM user
                          WHERE id = ?      
                          ");
    $res->execute([$id]);
    return $res->fetch();
}

 

Thank you for this.  You will be happy to know that i am now using the function($pdo, $var, $var) way of working.  Should probably have included in the previous post.

 

Single function - got it.

Link to comment
Share on other sites

18 minutes ago, Adamhumbug said:

Should probably have included in the previous post.

Yes. Instead of saying this...

1 hour ago, Adamhumbug said:

The database connection comment was more about each function having to establish a connection and send a query to the database

 

 

Link to comment
Share on other sites

There are design patterns like Model-View-Controller (MVC) that already address these ideas.  Most frameworks implement the MVC pattern.

How is this relevant to you?

Your user data structure should be described in a "User" model class.  

Frameworks give you a lot of base class functionality, but even without using a framework, you should be able to take the idea, and create your own.

The models of the popular frameworks are otherwise known as "object relational mapper" aka ORM libraries, and of these there are a couple different pattern flavors:  the Data Mapper pattern (example: Doctrine ORM, Cycle ORM) or the Active Record pattern (Laravel Eloquent, CakePHP, others).

Looking into the API's these libraries provide, can be the basis of your own home-grown highly simplified model classes.  The important idea to grasp, is that a model class in an ORM is the blueprint for how relational data is mapped to a php object when read, and stored into the database (or deleted) when written.

The popular ORM's do a lot more than that, but as a starting point it's good to just think about those simple needs.

To the point of setters and getters this often comes down to philosophy and pragmatism.  It is entirely possible to create a model class for a table that uses one or both of the __get and __set magic methods to provide you with $user->getCol1() and $user->setCol1() functionality without having to actually implement those methods.

Conversely however, most ORM's require you to provide the attributes and setter/getter functions, and there are certainly cases where those are valuable to have.  

However, when all is said and done, the bigger question is:  why don't you use one of these many ORM libraries instead of rolling your own ill conceived libraries?

 

Link to comment
Share on other sites

4 hours ago, gizmola said:

There are design patterns like Model-View-Controller (MVC) that already address these ideas.  Most frameworks implement the MVC pattern.

How is this relevant to you?

Your user data structure should be described in a "User" model class.  

Frameworks give you a lot of base class functionality, but even without using a framework, you should be able to take the idea, and create your own.

The models of the popular frameworks are otherwise known as "object relational mapper" aka ORM libraries, and of these there are a couple different pattern flavors:  the Data Mapper pattern (example: Doctrine ORM, Cycle ORM) or the Active Record pattern (Laravel Eloquent, CakePHP, others).

Looking into the API's these libraries provide, can be the basis of your own home-grown highly simplified model classes.  The important idea to grasp, is that a model class in an ORM is the blueprint for how relational data is mapped to a php object when read, and stored into the database (or deleted) when written.

The popular ORM's do a lot more than that, but as a starting point it's good to just think about those simple needs.

To the point of setters and getters this often comes down to philosophy and pragmatism.  It is entirely possible to create a model class for a table that uses one or both of the __get and __set magic methods to provide you with $user->getCol1() and $user->setCol1() functionality without having to actually implement those methods.

Conversely however, most ORM's require you to provide the attributes and setter/getter functions, and there are certainly cases where those are valuable to have.  

However, when all is said and done, the bigger question is:  why don't you use one of these many ORM libraries instead of rolling your own ill conceived libraries?

 

Thanks for this - the simple answer is that i have learned a language (learning) and i am yet to have any expereience of the concepts that you are describing.  I havnt yet explored the world of OOP and clearly this is something that i will need to have a look into.  I havnt used any frameworks at all.

I think this is going to need to be something that i explore to help me move from very amateur.

I appreciate your comments and i will certainly look at adding frameworks to the reading list while i try to "master" the basics.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.