You need to understand that there are much more things to do here than just define the User
class.
The general flow for the web app is something like this:
- User enters his data on the registration form
- Form is POSTed to your php code
- You application class routes the POST request to the specific code which handles user registration
- User data is validated, if something is wrong, the error response is sent back to the browser
- User data is saved to the database
- User session is started, so your application knows that he/she is logged in
- Successful response is sent to the browser (or your code redirect browser to the profile page)
Now, on the code level, there will be many objects.
I assume that your application will have a single entry point, some base index.php
file which accepts all the requests and then routes to the handlers.
So you will have (this is not a real code, just a structure):
index.php
$app = new WebApplication();
$app->run();
framework/Application.php
class WebApplication {
public function run() {
$request = new Request(); // will parse data from $_GET, $_POST, etc
$router = new UrlRouter($request);
$controller = $router->resolveRequest(); // according to the rules you define, it will find
// what controller to create
// controllers handle specific requests
$controller->run();
}
}
framework/Controller.php
class Controller { // You will have a base class for controllers
// ...
}
application/controllers/UserController.php
class UserController extends Controller {
public function actionRegister() {
// Create user validator and pass the Request object into it
$validator = UserValidator($this->getRequest());
if (!$validator->validate()) {
// render the HTML with error
$this->render('error', array('message'=>$validator->getError()));
// OR send as json
$this->sendJson(array(
'status'=>'error', 'message'=>$validator->getError()
));
} else {
$user = new User(
$this->getRequest()->get('email'),
$this->getRequest()->get('password')
// ...
);
$dbTable = new UsersTable();
$dbTable->save($user);
$this->startSession($user);
}
}
application/models/User.php
class User extends Model {
protected $email;
protected $firstname;
//...
public function __construct($email, $password) {
// ...
}
}
And so on, we need to define UserValidator
, UserTable
and everything else.
So the User
class in your question is only a small part of the big picture.
If you want to do the OOP properly, you are going to have a lot of classes and objects.
They may be similar to what I describe above or they may differ a lot, but the overall idea will be the same - the features you need should be split over a relatively small objects and you combine them to build your application.
If you want to do this, the best thing is to learn how it is done in popular frameworks. You don't need to dive deep from the start and learn the code, just go through the few tutorials to see how it looks for the framework user.