Assignments On Class 34:
PHP and MVC Pattern
Assignments on PHP and MVC Pattern with Step-by-Step Solutions
Here are some assignments based
on the MVC concept discussed above, along with step-by-step solutions and
explanations.
Assignment
1: Extend the MVC application to allow users to update their profile
Objective:
Enhance the existing MVC
application so that users can update their profile information.
Steps:
1. Model
Update:
o
Add a method to the UserModel class to update user data in the
database.
Solution:
php
Copy code
// models/UserModel.php
class UserModel {
private $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root',
'', 'mvc_example');
}
public function getUserData($userId) {
$query = "SELECT * FROM users
WHERE id = $userId";
$result = $this->db->query($query);
return $result->fetch_assoc();
}
// New Method: Update user data
public function updateUser($userId, $name, $email)
{
$query = "UPDATE users SET name =
'$name', email = '$email' WHERE id = $userId";
$this->db->query($query);
}
}
2. Controller
Update:
o
Add a method in the UserController class to handle the form
submission and update the profile data.
Solution:
php
Copy code
// controllers/UserController.php
class UserController {
public function showProfile($userId) {
$userModel = new UserModel();
$user = $userModel->getUserData($userId);
include 'views/user_profile.php';
}
// New Method: Handle profile update
public function updateProfile($userId) {
if (isset($_POST['name']) && isset($_POST['email']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$userModel = new UserModel();
$userModel->updateUser($userId, $name,
$email);
echo "Profile updated
successfully!";
} else {
echo "All fields are
required.";
}
}
}
3. View
Update:
o
Add a form to the user_profile.php to allow users to input new name
and email information.
Solution:
php
Copy code
<!-- views/user_profile.php
-->
<h1>User Profile</h1>
<p>Name: <?php echo $user['name'];
?></p>
<p>Email: <?php echo $user['email'];
?></p>
<!-- Form for updating profile
-->
<form method="POST"
action="index.php?action=updateProfile&user_id=<?php echo $user['id'];
?>">
<label for="name">Name:
</label>
<input type="text" name="name"
value="<?php echo $user['name']; ?>" required>
<br>
<label for="email">Email:
</label>
<input type="email" name="email"
value="<?php echo $user['email']; ?>" required>
<br>
<button type="submit">Update
Profile</button>
</form>
4. Entry
Point Update:
o
Modify the index.php to handle the new action (updateProfile).
Solution:
php
Copy code
// index.php
require_once 'models/UserModel.php';
require_once 'controllers/UserController.php';
if (isset($_GET['action'])
&& isset($_GET['user_id'])) {
$userId = $_GET['user_id'];
$controller = new UserController();
// Handle different actions
if ($_GET['action'] == 'updateProfile') {
$controller->updateProfile($userId);
} else {
echo "Action not recognized";
}
} else {
echo 'User ID not provided or invalid
action';
}
Explanation:
- Model: We
added a method updateUser in the UserModel to
update the user’s name and email in the database.
- Controller: The
updateProfile
method in the controller handles the POST request, calls the model’s updateUser
method, and displays a success message.
- View: The
user_profile.php
view now includes a form for updating the user’s information, pre-filled
with the current data.
- Entry
Point: The index.php now checks for the action=updateProfile and
calls the appropriate controller method.
Assignment
2: Implement a Simple Routing System for Multiple Pages
Objective:
Implement a simple routing system
so the user can navigate to different pages, like a homepage or profile page,
based on the URL.
Steps:
1. Create
Additional Views:
o
Create a homepage view (home.php) to
display the homepage content.
Solution:
php
Copy code
<!-- views/home.php -->
<h1>Welcome to the Home
Page</h1>
<p>Click the link below to
view your profile:</p>
<a href="index.php?action=showProfile&user_id=1">Go
to Profile</a>
2. Modify
the Controller to Handle Multiple Actions:
o
Update the UserController to handle different actions for
homepage and profile pages.
Solution:
php
Copy code
// controllers/UserController.php
class UserController {
// Show homepage
public function showHome() {
include 'views/home.php';
}
// Show user profile
public function showProfile($userId) {
$userModel = new UserModel();
$user = $userModel->getUserData($userId);
include 'views/user_profile.php';
}
}
3. Entry
Point Update with Routing Logic:
o
Implement a simple routing mechanism in index.php to
direct the user to the appropriate page based on the action query
parameter.
Solution:
php
Copy code
// index.php
require_once 'models/UserModel.php';
require_once 'controllers/UserController.php';
if (isset($_GET['action'])) {
$controller = new UserController();
// Simple Routing Logic
if ($_GET['action'] == 'showHome') {
$controller->showHome();
} elseif ($_GET['action'] == 'showProfile'
&& isset($_GET['user_id'])) {
$userId = $_GET['user_id'];
$controller->showProfile($userId);
} else {
echo 'Action not recognized';
}
} else {
echo 'No action specified';
}
4. Test the
Application:
o
Navigate to index.php?action=showHome to view
the homepage.
o
Navigate to index.php?action=showProfile&user_id=1 to view
the profile page.
Explanation:
- Model: No
changes were made to the model.
- Controller: The
controller now handles the showHome action, which loads the
homepage, in addition to the showProfile action for displaying the
profile page.
- View: A
new view (home.php) was created for the
homepage.
- Entry
Point: The routing logic in index.php
checks the action query parameter and routes
the user to the correct controller method.
Assignment
3: Create a User Registration Feature
Objective:
Implement a simple user
registration feature where users can sign up and have their information saved
to the database.
Steps:
1. Model
Update:
o
Add a method to the UserModel class to insert a new user into
the database.
Solution:
php
Copy code
// models/UserModel.php
class UserModel {
private $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root',
'', 'mvc_example');
}
public function registerUser($name, $email,
$password) {
$passwordHash = password_hash($password,
PASSWORD_DEFAULT); // Hash password before saving
$query = "INSERT INTO users (name,
email, password) VALUES ('$name', '$email', '$passwordHash')";
$this->db->query($query);
}
}
2. Controller
Update:
o
Add a method in the UserController class to handle the registration
form submission.
Solution:
php
Copy code
// controllers/UserController.php
class UserController {
public function showRegistrationForm() {
include 'views/registration_form.php';
}
public function registerUser() {
if (isset($_POST['name']) && isset($_POST['email'])
&& isset($_POST['password'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$userModel = new UserModel();
$userModel->registerUser($name, $email,
$password);
echo "User registered
successfully!";
} else {
echo "All fields are
required.";
}
}
}
3. View
Update:
o
Add a form in registration_form.php to allow users to input their
registration details.
Solution:
php
Copy code
<!--
views/registration_form.php -->
<h1>Registration
Form</h1>
<form method="POST"
action="index.php?action=registerUser">
<label for="name">Name:
</label>
<input type="text" name="name"
required>
<br>
<label for="email">Email:
</label>
<input type="email" name="email"
required>
<br>
<label for="password">Password:
</label>
<input type="password" name="password"
required>
<br>
<button type="submit">Register</button>
</form>
4. Entry
Point Update:
o
Modify index.php to handle the registration
action.
Solution:
php
Copy code
// index.php
require_once 'models/UserModel.php';
require_once 'controllers/UserController.php';
if (isset($_GET['action'])) {
$controller = new UserController();
if ($_GET['action'] == 'showRegistrationForm')
{
$controller->showRegistrationForm();
} elseif ($_GET['action'] == 'registerUser'
&& $_SERVER['REQUEST_METHOD'] == 'POST') {
$controller->registerUser();
} else {
echo 'Action not recognized';
}
} else {
echo 'No action specified';
}
Explanation:
- Model: We
added the registerUser method to insert user data
into the database. Password is hashed for security.
- Controller: The
registerUser
method handles the form submission, validates input, and calls the model's
registerUser
method to save the data.
- View: The
registration_form.php
view contains the registration form.
- Entry
Point: The index.php entry point is modified to
handle the registerUser action.
These assignments provide
hands-on practice with key concepts in MVC architecture, including models,
controllers, views, routing, and user interaction handling.
4o mini
You said:
Give more
ChatGPT
said:
ChatGPT
Here are additional assignments
on the PHP and MVC pattern, along with step-by-step solutions and
explanations.
Assignment
4: Implement User Login and Authentication
Objective:
Create a simple login system
where users can log in using their credentials and access a restricted page.
Steps:
1. Model
Update:
o
Add a method in the UserModel class to authenticate a user.
Solution:
php
Copy code
// models/UserModel.php
class UserModel {
private $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root',
'', 'mvc_example');
}
// Method to authenticate a user
public function authenticate($email, $password)
{
$query = "SELECT * FROM users
WHERE email = '$email'";
$result = $this->db->query($query);
$user = $result->fetch_assoc();
if ($user && password_verify($password,
$user['password'])) {
return $user; // Authentication successful
}
return false; // Authentication failed
}
}
2. Controller
Update:
o
Add methods in UserController for login form display,
authentication, and post-login redirection.
Solution:
php
Copy code
// controllers/UserController.php
class UserController {
// Show login form
public function showLoginForm() {
include 'views/login_form.php';
}
// Handle login authentication
public function login() {
if (isset($_POST['email']) && isset($_POST['password']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$userModel = new UserModel();
$user = $userModel->authenticate($email,
$password);
if ($user) {
$_SESSION['user_id'] = $user['id']; // Store user session
header('Location:
index.php?action=dashboard');
exit;
} else {
echo "Invalid
credentials!";
}
}
}
// Show dashboard after login
public function dashboard() {
if (!isset($_SESSION['user_id'])) {
header('Location:
index.php?action=showLoginForm');
exit;
}
echo "Welcome to your
Dashboard!";
}
}
3. View
Update:
o
Create a login form view (login_form.php).
Solution:
php
Copy code
<!-- views/login_form.php
-->
<h1>Login</h1>
<form method="POST"
action="index.php?action=login">
<label for="email">Email:
</label>
<input type="email" name="email"
required>
<br>
<label for="password">Password:
</label>
<input type="password" name="password"
required>
<br>
<button type="submit">Login</button>
</form>
4. Session
Start and Entry Point Update:
o
Start the session and modify index.php to
handle login and dashboard actions.
Solution:
php
Copy code
// index.php
session_start();
require_once 'models/UserModel.php';
require_once 'controllers/UserController.php';
if (isset($_GET['action'])) {
$controller = new UserController();
if ($_GET['action'] == 'showLoginForm') {
$controller->showLoginForm();
} elseif ($_GET['action'] == 'login'
&& $_SERVER['REQUEST_METHOD'] == 'POST') {
$controller->login();
} elseif ($_GET['action'] == 'dashboard')
{
$controller->dashboard();
} else {
echo 'Action not recognized';
}
} else {
echo 'No action specified';
}
Explanation:
- Model: The
authenticate method
checks the user’s credentials by comparing the entered password (after
hashing) with the stored password.
- Controller: The
login
method authenticates the user, and if successful, stores the user’s
session and redirects to a dashboard page.
- View: The
login_form.php
provides a login form for users to input their credentials.
- Entry
Point: The index.php routes actions for login,
authentication, and the dashboard.
Assignment
5: Create a User Registration, Login, and Logout System
Objective:
Develop a complete user system
where users can register, log in, and log out.
Steps:
1. Model
Update:
o
Add methods in the UserModel class for user registration,
login, and logout.
Solution:
php
Copy code
// models/UserModel.php
class UserModel {
private $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root',
'', 'mvc_example');
}
// Method to register a new user
public function registerUser($name, $email,
$password) {
$passwordHash = password_hash($password,
PASSWORD_DEFAULT);
$query = "INSERT INTO users (name,
email, password) VALUES ('$name', '$email', '$passwordHash')";
$this->db->query($query);
}
// Method to authenticate user login
public function authenticate($email, $password)
{
$query = "SELECT * FROM users
WHERE email = '$email'";
$result = $this->db->query($query);
$user = $result->fetch_assoc();
if ($user && password_verify($password,
$user['password'])) {
return $user;
}
return false;
}
// Method to logout by destroying session
public function logout() {
session_unset();
session_destroy();
}
}
2. Controller
Update:
o
Add methods for handling registration, login, and
logout.
Solution:
php
Copy code
// controllers/UserController.php
class UserController {
// Show registration form
public function showRegistrationForm() {
include 'views/registration_form.php';
}
// Register a new user
public function register() {
if (isset($_POST['name']) && isset($_POST['email'])
&& isset($_POST['password'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$userModel = new UserModel();
$userModel->registerUser($name, $email,
$password);
echo "User registered
successfully!";
}
}
// Show login form
public function showLoginForm() {
include 'views/login_form.php';
}
// Handle login
public function login() {
if (isset($_POST['email']) && isset($_POST['password']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$userModel = new UserModel();
$user = $userModel->authenticate($email,
$password);
if ($user) {
$_SESSION['user_id'] = $user['id'];
header('Location: index.php?action=dashboard');
exit;
} else {
echo "Invalid
credentials!";
}
}
}
// Logout the user
public function logout() {
$userModel = new UserModel();
$userModel->logout();
header('Location:
index.php?action=showLoginForm');
}
// Show dashboard after login
public function dashboard() {
if (!isset($_SESSION['user_id'])) {
header('Location:
index.php?action=showLoginForm');
exit;
}
echo "Welcome to your
Dashboard!";
}
}
3. View
Update:
o
Add registration and login forms.
Solution (Registration Form):
php
Copy code
<!--
views/registration_form.php -->
<h1>Register</h1>
<form method="POST"
action="index.php?action=register">
<label for="name">Name:
</label>
<input type="text" name="name"
required>
<br>
<label for="email">Email:
</label>
<input type="email" name="email"
required>
<br>
<label for="password">Password:
</label>
<input type="password" name="password"
required>
<br>
<button type="submit">Register</button>
</form>
Solution (Login Form):
php
Copy code
<!-- views/login_form.php
-->
<h1>Login</h1>
<form method="POST"
action="index.php?action=login">
<label for="email">Email:
</label>
<input type="email" name="email"
required>
<br>
<label for="password">Password:
</label>
<input type="password" name="password"
required>
<br>
<button type="submit">Login</button>
</form>
4. Session
and Entry Point Update:
o
Start the session and modify index.php to
handle registration, login, logout, and dashboard actions.
Solution:
php
Copy code
// index.php
session_start();
require_once 'models/UserModel.php';
require_once 'controllers/UserController.php';
if (isset($_GET['action'])) {
$controller = new UserController();
if ($_GET['action'] == 'showRegistrationForm')
{
$controller->showRegistrationForm();
} elseif ($_GET['action'] == 'register'
&& $_SERVER['REQUEST_METHOD'] == 'POST') {
$controller->register();
} elseif ($_GET['action'] == 'showLoginForm')
{
$controller->showLoginForm();
} elseif ($_GET['action'] == 'login'
&& $_SERVER['REQUEST_METHOD'] == 'POST') {
$controller->login();
} elseif ($_GET['action'] == 'logout') {
$controller->logout();
} elseif ($_GET['action'] == 'dashboard') {
$controller->dashboard();
} else {
echo 'Action not recognized';
}
} else {
echo 'No action specified';
}
Explanation:
- Model: The
registerUser
method allows users to register with hashed passwords. The authenticate
method checks if credentials are valid, and logout
clears the session.
- Controller: The
controller handles registration, login, dashboard display, and logout.
- View: The
registration_form.php and
login_form.php are
simple forms for user input.
- Entry
Point: The index.php controls routing, such as
registration, login, and logout, and redirects to the dashboard after
successful login.
These assignments help students
build a foundational understanding of MVC architecture in PHP while gaining
practical experience by creating common user management features such as
registration, login, and logout.