I have following problem / question. I am working on my Webshop project (Plain PHP MySQL), and I’ve build so far registration, login, products and so on using MVC Pattern / Model. When the user logs in, it’s going to save the email only to session ( $_SESSION[ $customerReposutory->getEmail()] ), and going to redirect to dashboard. The problem is, I want to display some information (for instance first name, and last name), and to make a Welcome Message for user inside Dashboard.
I made this function, that is going to look for user that is logged in.
public function userData(string $email)
{
return $this->customerRepository->getByEmail($email);
}
Afterward its called inside Dashboard Controller:
public function dashboard(): void {
$this->loginService->accessDashboard();
//Get E-Mail from session
$getLoginInfo=$_SESSION['login'];
//Look for users with particular email
$firstName=$this->loginService->userData($getLoginInfo);
//Render to View
$this->render('dashboard', ['firstName'=>$firstName]); }
Repository:
public function getByEmail(string $email)
{
$tableName = $this->setTableName();
$className = $this->setClassName();
$statement = $this->connection->prepare("SELECT * FROM `$tableName` WHERE email=:email");
$statement->execute(['email' => $email]);
//Customer Model -> id, first name, last name, password, email
$statement->setFetchMode(PDO::FETCH_CLASS, $className);
return $statement->fetch(PDO::FETCH_CLASS);
}
What I want is, to access information via Model (class) inside View
$customer->getFirstName() and not as object $customer->first name.
Right now, only E-Mail method is accessible from model: $customer->getEmail()
Thanks for your time!
CodePudding user response:
accessing it like this:
ClassName::$first_name;
// ClassName is your class name
If that doesn't work you can try making the first name a static property:
public static $first_name = "whatever";
EDIT: By making it static you cannot access it from an object.
CodePudding user response:
You are getting the user via
$statement = $this->connection->prepare("SELECT * FROM `$tableName` WHERE email=:email");
$statement->execute(['email' => $email]);
but you never store it. Get the results, like this:
// select a particular user by id
$stmt = $pdo->prepare("SELECT <YOUR COLUMNS HERE> FROM `$tableName` WHERE email=:email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();
As a result, you will have a $user variable which will contain all the information you need. So, you will need to instantiate your model class and call its setters to set its values based on what you have inside $user. Once you have such an instance, you will be able to use it and get its attributes via calling some getters.
