Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views15 pages

Chapter 8

Chapter 8 of 'Internet Programming II' covers Object-Oriented Programming (OOP) in PHP, detailing its core concepts such as classes, objects, encapsulation, inheritance, polymorphism, and MVC architecture. It emphasizes the advantages of OOP, including reusability, maintainability, and scalability, while also explaining advanced topics like namespaces, autoloading, and the MVC design pattern. The chapter illustrates how OOP principles can be applied to structure PHP applications effectively.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views15 pages

Chapter 8

Chapter 8 of 'Internet Programming II' covers Object-Oriented Programming (OOP) in PHP, detailing its core concepts such as classes, objects, encapsulation, inheritance, polymorphism, and MVC architecture. It emphasizes the advantages of OOP, including reusability, maintainability, and scalability, while also explaining advanced topics like namespaces, autoloading, and the MVC design pattern. The chapter illustrates how OOP principles can be applied to structure PHP applications effectively.

Uploaded by

agetachew97
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Internet Programming II - 2017EC

Chapter 8
OBJECT-ORIENTED PHP & MVC ARCHITECTURE
8.1. Introduction
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects",
which can contain data (properties) and code (methods).

In PHP, OOP allows you to structure your code into modular, reusable pieces, making it easier to manage,
extend, and debug.

OOP offers several key advantages that improve the quality and structure of your code, these include:

 Reusability: You can reuse classes and objects across different parts of your application.
 Maintainability: Code is easier to read and maintain when organized into objects.
 Scalability: OOP makes it easier to scale up applications by separating concerns.
 Real-world modeling: Objects can represent real-world entities, making your code more intuitive.

Procedural vs. Object-Oriented PHP

Procedural PHP Object-Oriented PHP

Code is written as a series of functions. Code is organized into classes and objects.

Data and functions are separate. Data and methods are bundled together inside objects.

Harder to reuse code across the application. High reusability through inheritance and modular design.

Difficult to maintain in large applications. Easier to maintain and extend large applications.

Commonly used for simple scripts and utilities. Ideal for building complex and scalable applications.

1 of 15
Internet Programming II - 2017EC

8.2. Core Concepts of OOP in PHP


Classes and Objects

Defining a Class

A class is a blueprint for creating objects. It defines the properties (variables) and methods (functions)
that its objects will have.

class Car {
public $brand;

public function drive() {


echo "The car is moving";
}
}
Creating Objects

Once a class is defined, you can create objects (instances) of that class.

$myCar = new Car();


$myCar->brand = "Toyota";
echo $myCar->brand; // Output: Toyota

Properties and Methods are key elements of a class in object-oriented programming. Properties, which
are variables declared inside a class, define the data or state of an object. Methods, which are functions
inside a class, define the behavior or actions that the object can perform. Together, they describe what
the object knows and what it can do.

Encapsulation

Encapsulation means restricting direct access to some components of an object. This protects data and
promotes security.

 public: Accessible from anywhere.

 private: Accessible only within the class.

 protected: Accessible within the class and by subclasses.

class Person {
public $age; // Public: Accessible from anywhere

2 of 15
Internet Programming II - 2017EC

private $name; // Private: Accessible only inside this class


protected $email; // Protected: Accessible in this class and child
classes

// Public method to set private and protected properties


public function setDetails($name, $email, $age) {
$this->name = $name;
$this->email = $email;
$this->age = $age;
}

// Public method to get private and protected properties


public function getDetails() {
return "Name: {$this->name}, Email: {$this->email}, Age: {$this-
>age}";
}
}

// Child class
class Employee extends Person {
public function getEmail() {
// Accessing protected property inside child class
return $this->email;
}
}

$person = new Person();


$person->age = 30; // Allowed (public)
$person->setDetails("Alice", "[email protected]", 30);

echo $person->getDetails(); // Works

// Direct access
echo $person->age; // Allowed (public)
// echo $person->name; // Error (private)
// echo $person->email; // Error (protected)

$employee = new Employee();

3 of 15
Internet Programming II - 2017EC

$employee->setDetails("Bob", "[email protected]", 28);


echo $employee->getEmail(); // Access protected property from child class
Getters and Setters

In object-oriented programming, getters and setters are special methods used to access and modify
private or protected properties of a class. Since direct access to these properties is restricted for the sake
of encapsulation, getters and setters provide a controlled way to interact with an object's internal state.
A getter method retrieves (or "gets") the value of a property, while a setter method updates (or "sets")
the value. This approach not only protects the data but also allows you to add validation or other logic
when properties are accessed or modified. For example, you might prevent setting a negative age or
automatically format a string before saving it.

Example:

class User {
private $email;

public function setEmail($email) {


if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
} else {
echo "Invalid email address.";
}
}

public function getEmail() {


return $this->email;
}
}
In this example, the setEmail() method checks whether the email is valid before setting it, while the
getEmail() method simply returns the stored value. This demonstrates how getters and setters help

enforce data integrity and encapsulation.

Inheritance

Inheritance allows a class to use the properties and methods of another class. A child class can inherit
from a parent class using the extends keyword.

4 of 15
Internet Programming II - 2017EC

Example:

class Animal {
public function sound() {
echo "Animal sound";
}
}

class Dog extends Animal {


public function bark() {
echo "Woof!";
}
}
The parent class has a method called sound(), the child object can access it using $dog->sound(). At
the same time, the child class can introduce its own methods, such as $dog->bark(), which provide
additional or specialized behaviors unique to the child class.

Polymorphism & Method Overriding

Polymorphism means the same method name can behave differently in different classes. A child class can
override a method from the parent class.

class Animal {
public function makeSound() {
echo "Some sound";
}
}

class Cat extends Animal {


public function makeSound() {
echo "Meow";
}
}

$pet = new Cat();


$pet->makeSound(); // Output: Meow

5 of 15
Internet Programming II - 2017EC

This is method overriding, where the child class provides its own implementation.

8.3. Other OOP Concepts in PHP


Constructors and Destructors

A constructor is a special method that automatically runs when an object of a class is created. It is used to
initialize properties or run setup code. In PHP, constructors are defined using the __construct()
method.

class Book {
public $title;

public function __construct($title) {


$this->title = $title;
}
}

$book = new Book("PHP Programming");


echo $book->title; // Output: PHP Programming

A destructor is another special method, defined with __destruct(), which is called automatically when
an object is destroyed or the script ends. It is often used to release resources like closing a file or database
connection.

class Demo {
public function __destruct() {
echo "Object destroyed.";
}
}

$demo = new Demo();

Static Properties and Methods

Static properties and methods belong to the class itself rather than to any object created from the class.
They are accessed using the class name, not an object instance.

6 of 15
Internet Programming II - 2017EC

 Static property is declared with the static keyword.


 Static method is also declared with static, and can be called without creating an object.

class Math {
public static $pi = 3.14;

public static function add($a, $b) {


return $a + $b;
}
}

echo Math::$pi; // Output: 3.14


echo Math::add(5, 10); // Output: 15

Static members are useful for utility functions and constant values shared across the program.

Abstract Classes and Interfaces

An abstract class cannot be instantiated directly. It is meant to be extended by child classes. Abstract
classes may contain abstract methods, which are method declarations without bodies; child classes must
implement them.

abstract class Animal {


abstract public function makeSound();
}

class Dog extends Animal {


public function makeSound() {
echo "Bark!";
}
}
An interface defines a contract that classes must follow. A class that implements an interface must provide
implementations for all its methods.

interface Shape {
public function area();
}

class Circle implements Shape {

7 of 15
Internet Programming II - 2017EC

public function area() {


return "Calculating area of Circle";
}
}
Interfaces are useful when different classes must follow a similar structure but have different
implementations.

Traits in PHP

Traits are a mechanism for code reuse in PHP. They allow you to include methods into multiple classes
without using inheritance. This solves the problem when you want a class to inherit behavior from
multiple sources.

trait Logger {
public function log($message) {
echo "Log message: $message";
}
}

class User {
use Logger;
}

$user = new User();


$user->log("User created."); // Output: Log message: User created.
Traits are very powerful when you want to share common methods between classes without forcing them
into an inheritance relationship.

8.4. Namespaces
Purpose of Namespaces

As projects grow larger, it's common to have many classes, functions, or constants that might accidentally
have the same name. Namespaces are used to group related code together and avoid name conflicts
between different parts of an application or between different libraries. Think of namespaces like folders
in a computer, they organize files (classes/functions) into separate spaces so they don't collide with each

8 of 15
Internet Programming II - 2017EC

other. Without namespaces, two classes named User from different libraries would cause an error. With
namespaces, both can exist safely under different labels.

Defining and Using Namespaces

You define a namespace at the top of a PHP file using the namespace keyword:

<?php
namespace App\Models;

class User {
public function getName() {
return "User from Models";
}
}
?>
In this example the App\Models is the namespace and the User class belongs to App\Models.

When you want to use a class from a namespace, you can either refer to its full name (with namespace):

$user = new \App\Models\User();

Or, import it with the use keyword (easier and cleaner):

use App\Models\User;
$user = new User();
The use Keyword and Autoload Compatibility

The use keyword allows you to import a class, function, or constant from a namespace so you don't have
to type its full name every time.

Example:

use App\Controllers\HomeController;

$controller = new HomeController();


You can also alias classes if two classes have the same name:

9 of 15
Internet Programming II - 2017EC

use LibraryOne\User as UserOne;


use LibraryTwo\User as UserTwo;

$user1 = new UserOne();


$user2 = new UserTwo();

Namespaces and Autoloading

Modern PHP applications (especially those following PSR-4 standards) often use autoloaders to
automatically load class files based on their namespace and directory structure.

Example:

 Namespace App\Models\User would map to the file path App/Models/User.php.

Composer (a PHP dependency manager) handles autoloading automatically by following this pattern,
saving you from manually including class files.

8.5. Autoloading Classes


Why Autoloading is Important

In small PHP projects, you might manually include each class file using require or include.
However, in larger applications with dozens or hundreds of classes, manually including files becomes
messy, hard to maintain, and error-prone.

Autoloading automatically loads the necessary class files when they are needed, without manually writing
require statements.

Autoloading improves efficiency by eliminating the need to manually include every file. It enhances
organization by loading classes only when they are needed and boosts performance by preventing
unnecessary loading of unused classes.

spl_autoload_register() Function

PHP provides a built-in function called spl_autoload_register() to make autoloading simple and
customizable. You register a function that PHP will call whenever it encounters a class that hasn’t been
loaded yet.

10 of 15
Internet Programming II - 2017EC

Example:

spl_autoload_register(function ($className) {
include $className . '.php';
});

$user = new User(); // If User class is not loaded, PHP will now include
"User.php"
In this example:

 If PHP tries to use a class User, it automatically tries to include the file User.php.

You can customize the autoloader to match your folder structure, making it easy to load classes from
specific directories.

Composer and PSR-4 Autoloading

Composer is the most popular dependency manager for PHP. One of its features is that it automatically
generates an autoloader for your classes based on PSR-4 standards. PSR-4 is a standard that maps a
namespace to a folder structure.

Example:

 Namespace: App\Models\User
 Maps to file: App/Models/User.php

Composer reads your namespace and class name and knows exactly where to find and load the file.

Setting Up Autoloading with Composer

Inside composer.json:

"autoload": {
"psr-4": {
"App\\": "src/"
}
}
After setting this up, you run:

composer dump-autoload

Composer will then autoload any class under the App\ namespace from the src/ directory.

11 of 15
Internet Programming II - 2017EC

8.6. Introduction to MVC Architecture


MVC stands for Model-View-Controller, a popular design pattern used to separate an application into
three interconnected components:

Model: Handles the data and business logic. It communicates with the database, processes data, and
responds to requests from the controller.

View: Handles what the user sees. It presents data from the model in a user-friendly format, usually as
HTML pages or templates.

Controller: Acts as a bridge between the Model and the View. It receives user input (like a form
submission), processes it (possibly using the Model), and returns the appropriate View.

Using the MVC pattern provides several important benefits:

 Separation of concerns means each component has a clear responsibility, making the application
easier to develop and maintain.
 Code reusability allows models, views, and controllers to be reused across different parts of the
application.
 Simplified collaboration happens when frontend developers work on Views while backend
developers focus on Models and Controllers.
 Scalability becomes easier because applications are organized and each part remains
independent.
 Testing is improved in MVC structures since logic is separated and easier to test individually.

In an MVC-based PHP project, the folder structure usually looks something like this:

12 of 15
Internet Programming II - 2017EC

/app
/Controllers
HomeController.php
UserController.php
/Models
User.php
Product.php
/Views
home.php
user.php
/public
index.php (entry point)

The Public folder contains the front-facing files like index.php, CSS, JavaScript, and images.

Example flow:

 User requests https://example.com/user/profile.


 index.php routes the request to UserController.

 UserController fetches user data from the User model.

 Data is sent to a user.php view to display.

8.7. Connecting OOP with MVC


How Classes Represent Models, Views, and Controllers

In an MVC architecture, OOP plays a role by structuring the application into different classes, each with a
specific responsibility:

Model Classes: Represent the data layer. They manage database operations like fetching, inserting,
updating, and deleting records.

Example: User, Product, or Order classes.

View Files/Classes: Responsible for displaying the output (HTML, JSON, etc.). In simple PHP MVC setups,
Views are usually files, but in more advanced systems, you can have View classes to manage templates.

Controller Classes: Handle user input, control the application's flow, interact with models, and select
which view to render.

13 of 15
Internet Programming II - 2017EC

Example: UserController, ProductController, etc.

Each part (Model, View, Controller) is organized into a separate class or set of files, following OOP
principles like encapsulation and separation of concerns.

Example:

Model => Class Interacting with a Database

<?php
namespace App\Models;

class User {
private $db;

public function __construct($databaseConnection) {


$this->db = $databaseConnection;
}

public function getUserById($id) {


// Simplified example (no prepared statements here for brevity)
$result = $this->db->query("SELECT * FROM users WHERE id = $id");
return $result->fetch_assoc();
}
}
?>

 The User model interacts with the database.


 It provides methods like getUserById() to fetch user data.

View => Class or File Generating HTML

<!-- app/Views/user.php -->


<!DOCTYPE html>
<html>
<head><title>User Profile</title></head>
<body>
<h1>User Profile</h1>
<p>Name: <?php echo htmlspecialchars($user['name']); ?></p>
<p>Email: <?php echo htmlspecialchars($user['email']); ?></p>
</body>

14 of 15
Internet Programming II - 2017EC

</html>

 This View displays the user's profile.


 It receives $user data from the controller and safely renders it in HTML.

Controller => Class Handling User Input and Routing

<?php
namespace App\Controllers;

use App\Models\User;

class UserController {
private $userModel;

public function __construct($databaseConnection) {


$this->userModel = new User($databaseConnection);
}

public function profile($id) {


$user = $this->userModel->getUserById($id);
include '../app/Views/user.php';
}
}
?>

 The UserController handles the request to view a user profile.


 It gets the user data from the User model and loads the appropriate view.

How the Pieces Connect

1. User accesses: https://example.com/user/profile/5


2. UserController is called, and its profile() method runs.
3. The controller uses the User model to fetch user data.
4. The controller includes the user.php view, passing the data for display.

15 of 15

You might also like