简体   繁体   中英

OOP/PHP - Selecting out of Database based on ID?

The title may be a little vague, but the question is difficult to word properly.

I'm trying to learn PHP OOP (coming from Procedural) and it's a pain - my main stump is selecting from a databased based on a certain value that is usually passed through the URL (at least in procedural).

For example, user.php?ID=2 - then I could quickly define ID using GET and future queries would use that ID.

Since my OOP classes would be in a seperate file to the main page that includes the html and outputs everything, users won't be submitting the ID to that file. In other words, they'll be going to user.php?ID=2 instead of user_c.php?ID=3 which is the class file.

My question is - how do I pass that ID through to the class? I need to select things out of the database based on the profile that they're viewing, but how do I tell the class that?

My apologies for how badly this is worded.

One would do something like this, $data now contains the data returned from the query:

//user_c.php:

Class MyUserClass {

   public function getUser($id){
        //Query for user data.
        return $queryData;
   }

}

//user.php

$userClass = new MyUserClass ();
$data = $userClass->getUser($_GET['ID']);

First of all, OOP is not that much different than procedural. The main difference is that instead of data and functions which operate on the data you have objects which encapsulate the data as well as the operations which are valid on that data.

However, in its core, OOP does encapsulate procedural programming, with the difference being that the procedural part happens within objects rather than in the application level.

To migrate from procedural to OOP all you need to do is separate your code in parts which are logically connected, in the case of databases what typically happens is each database table has a class (in MVC frameworks this is called a data model).

For example if you have a table called users you might have a corresponding User class.

class User {
      private $id;
      private $alsoOtherProperties;      

      public function __construct($dbconnection, $id) {
          //Load the user from id
      }
      /* Setters and getters and other function here which operate on the user */

}

You then create an instance of a user which you construct from the $id given the database connection. The simplest way is do what you're already doing to get the id. From here on your data will be operating on the User object rather than on a database result. This way you don't have to worry about changing the database structure since you can just update the model to work with the new structure and the rest of the code will not need altering.

For example, say you want to update the "last logged in" column for a user at the time of log in:

//Other code around here
$ID = $db->real_escape_string(strip_tags(stripslashes($_GET['ID'])));

$user = new User($db,ID);

$user->setLastLogin(time()); 

$user->save();

In this example there's 2 functions defined in the class User in addition to the constructor which is to set the last login time and then update the database row which corresponds to the user. As you can see, this does not have any MySQL specific logic and the underlying code in the user class can update either a MySQL database, a text file, or not do anything (eg when just running tests).

Note: This is just an example, probably not a very good one at that, you should really really study OOP to learn more about it.

Assuming that until now you did something like this:

// user.php

$id = $_GET['id'];

$myResult = myDbFunction($id);

function myDbFunction($id) {
    // do something useful
}

you can re-write this like that:

// user_c.php:

Class MyClass {
    public function myDbFunction($id) {
        $something = "";
        // do something useful
        return $something;
    }
}

// user.php:

include "user_c.php";

$myClass = new MyClass();

$id = $_GET['id'];

$myResult = $myClass->myDbFunction($id);

And that would produce the same results as if you had placed your class in the same file, like this:

// user.php:

Class MyClass {
    public function myDbFunction($id) {
        $something = "";
        // do something useful
        return $something;
    }
}


$myClass = new MyClass();

$id = $_GET['id'];

$myResult = $myClass->myDbFunction($id);

I assume you know that one of the main reasons for going OOP over procedural is the re-usability as well as information hiding (ie sparing a user of your class the need to understand every detail of it, while still allowing them to use it)

You may want to read up on OOP with PHP, and simply play around with it. While there is a slight differece in the two styles, you should get a hang of it quickly.

Once you make sure you understood the single responsibility principle and follow it, you will surely find that OOP has many advantages over procedural programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM