Welcome back to our PHP Object-Oriented Programming (OOP) series. In the previous article, we began constructing a database in MYSQL, and now we’re ready to delve into the next steps. In this part, we’ll be focusing on the User
class.
Class Definition:
Let’s create a User
class to handle database operations related to users. This will be in our User.php file.
class User {
// Class definition
}
Database Operations in User Class:
Get All Users:
Demonstrating how to retrieve all user records using a static method without instantiating the class.
class User {
public static function all() {
return Database::table('users')->select()->run();
}
}
Get User by ID:
Fetching a user by their ID, showcasing the intermediary role of the User
class between the application and the database.
class User {
public static function getById($id) {
return Database::table('users')->select()
->where('id = :id', ['id' => $id])
->run();
}
}
Get User by Email:
Extending functionalities with a method to retrieve a user by their email address.
class User {
public static function getByEmail($email) {
return Database::table('users')->select()
->where('email = :email', ['email' => $email])
->run();
}
}
Conclusion and Anticipation:
In this journey of simplifying database operations with PHP OOP, we’ve successfully crafted a robust User
class, streamlining interactions between our application and the database. This structured approach not only enhances code readability but also sets the stage for scalable and maintainable projects.
As we traverse this OOP adventure, our exploration is far from over. In the upcoming segment, we’ll unravel the intricacies of updating user records.