In this section, we will focus on implementing the backend logic for our web application. This involves writing the PHP code that will handle the core functionality of our application, such as processing user input, interacting with the database, and managing sessions.
Key Concepts
- Backend Logic: The server-side code that processes requests, performs operations, and returns responses.
- MVC Architecture: A design pattern that separates the application into three main components: Model, View, and Controller.
- Routing: The mechanism that maps URLs to specific functions or methods in your application.
- Controllers: Classes that handle incoming requests and return responses.
- Models: Classes that represent the data and business logic of the application.
- Views: Templates that generate the HTML output sent to the user's browser.
Step-by-Step Guide
- Setting Up the MVC Structure
First, let's set up the basic structure of our application following the MVC pattern.
project/ │ ├── app/ │ ├── Controllers/ │ ├── Models/ │ └── Views/ │ ├── public/ │ └── index.php │ └── config/ └── routes.php
- Configuring Routes
In the config/routes.php
file, define the routes for your application. Each route maps a URL to a specific controller and method.
<?php // config/routes.php $routes = [ '/' => 'HomeController@index', '/login' => 'AuthController@login', '/register' => 'AuthController@register', '/dashboard' => 'DashboardController@index', ]; return $routes; ?>
- Creating Controllers
Controllers handle the logic for each route. Let's create a simple HomeController
.
<?php // app/Controllers/HomeController.php class HomeController { public function index() { // Load the view include '../app/Views/home.php'; } } ?>
- Creating Models
Models represent the data and business logic. Here’s an example of a User
model.
<?php // app/Models/User.php class User { private $db; public function __construct($db) { $this->db = $db; } public function getUserById($id) { $stmt = $this->db->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$id]); return $stmt->fetch(); } } ?>
- Creating Views
Views generate the HTML output. Here’s a simple view for the home page.
<!-- app/Views/home.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Home</title> </head> <body> <h1>Welcome to the Home Page</h1> </body> </html>
- Handling Requests
In the public/index.php
file, handle incoming requests and route them to the appropriate controller.
<?php // public/index.php // Load routes $routes = include '../config/routes.php'; // Get the requested URL $url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // Find the corresponding controller and method if (array_key_exists($url, $routes)) { list($controller, $method) = explode('@', $routes[$url]); $controller = new $controller(); $controller->$method(); } else { // Handle 404 echo "404 Not Found"; } ?>
- Connecting to the Database
Ensure your application can connect to the database. Here’s a simple database connection setup.
<?php // config/database.php try { $db = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
- Example: User Registration
Let's implement a user registration feature.
Controller
<?php // app/Controllers/AuthController.php class AuthController { private $userModel; public function __construct() { include '../config/database.php'; $this->userModel = new User($db); } public function register() { if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = password_hash($_POST['password'], PASSWORD_BCRYPT); $this->userModel->createUser($username, $password); header('Location: /login'); } else { include '../app/Views/register.php'; } } } ?>
Model
<?php // app/Models/User.php class User { private $db; public function __construct($db) { $this->db = $db; } public function createUser($username, $password) { $stmt = $this->db->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); $stmt->execute([$username, $password]); } } ?>
View
<!-- app/Views/register.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> </head> <body> <h1>Register</h1> <form method="POST" action="/register"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <br> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <br> <button type="submit">Register</button> </form> </body> </html>
Practical Exercise
Task
- Implement a login feature following the same structure as the registration feature.
- Ensure that the user is redirected to the dashboard upon successful login.
Solution
Controller
<?php // app/Controllers/AuthController.php class AuthController { private $userModel; public function __construct() { include '../config/database.php'; $this->userModel = new User($db); } public function login() { if ($_SERVER['REQUEST_METHOD'] == 'POST') { $username = $_POST['username']; $password = $_POST['password']; $user = $this->userModel->getUserByUsername($username); if ($user && password_verify($password, $user['password'])) { session_start(); $_SESSION['user_id'] = $user['id']; header('Location: /dashboard'); } else { echo "Invalid credentials"; } } else { include '../app/Views/login.php'; } } } ?>
Model
<?php // app/Models/User.php class User { private $db; public function __construct($db) { $this->db = $db; } public function getUserByUsername($username) { $stmt = $this->db->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$username]); return $stmt->fetch(); } } ?>
View
<!-- app/Views/login.php --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h1>Login</h1> <form method="POST" action="/login"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <br> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <br> <button type="submit">Login</button> </form> </body> </html>
Conclusion
In this section, we have covered the basics of implementing backend logic in a PHP application using the MVC pattern. We set up the project structure, configured routes, created controllers, models, and views, and implemented a user registration feature. By following these steps, you can build robust and maintainable PHP applications.
Next, we will integrate our backend logic with a database to store and retrieve data efficiently.
PHP Programming Course
Module 1: Introduction to PHP
- What is PHP?
- Setting Up the Development Environment
- Your First PHP Script
- PHP Syntax and Variables
- Data Types in PHP
Module 2: Control Structures
Module 3: Functions
- Defining and Calling Functions
- Function Parameters and Return Values
- Variable Scope
- Anonymous Functions and Closures
Module 4: Arrays
Module 5: Working with Forms
Module 6: Working with Files
Module 7: Object-Oriented Programming (OOP)
- Introduction to OOP
- Classes and Objects
- Properties and Methods
- Inheritance
- Interfaces and Abstract Classes
- Traits
Module 8: Working with Databases
- Introduction to Databases
- Connecting to a MySQL Database
- Performing CRUD Operations
- Using PDO for Database Interaction
- Database Security
Module 9: Advanced PHP Techniques
- Error and Exception Handling
- Sessions and Cookies
- Regular Expressions
- Working with JSON and XML
- PHP and Web Services
Module 10: PHP Frameworks and Best Practices
- Introduction to PHP Frameworks
- Getting Started with Laravel
- MVC Architecture
- Best Practices in PHP Development
- Testing and Debugging