In PHP, an abstract class is a class that cannot be instantiated directly but serves as a blueprint for other classes to inherit from. It provides a way to define common properties and methods that should be shared among its subclasses. The purpose of an abstract class is to define a common interface and behavior that subclasses must implement.
An abstract class is declared using the abstract keyword before the class keyword.
For examples:
abstract class AbstractClass {
// class definition
}
Instantiating an abstract class directly using the 'new' keyword is not possible. In case you try to create an object of an abstract class, it will return the result in a fatal error.
An abstract class can have abstract methods. These methods are declared without a body and must be implemented in the concrete subclasses that extend the abstract class. Abstract methods are defined using the abstract keyword before the method declaration.
For Examples:
abstract class AbstractClass {
abstract public function abstractMethod();
}
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
abstract public function makeSound();
}
class Dog extends Animal {
public function makeSound() {
return 'Woof every time and some time WoofWoooof!';
}
}
class Cat extends Animal {
public function makeSound() {
return 'Meow every time some time MeowMeowwww..!';
}
}
// Creating instances of derived classes but it's not working
$dog = new Dog('charlie');
$cat = new Cat('Whiskers');
echo $dog->makeSound(); // Output: Woof!
echo $cat->makeSound(); // Output: Meow!
In the example above, the Animal class is defined as an abstract class using the abstract keyword. It has an abstract method "makeSound()", which is declared but does not have an implementation in the abstract class. The derived classes Dog and Cat inherit from Animal and must provide an implementation for the "makeSound()" method.
Note that an abstract method does not have a body; it only declares the method signature. Any class that inherits from an abstract class must implement all abstract methods defined in the parent class, or else it will also be considered abstract.
You cannot create an instance of an abstract class. Instead, you create instances of the derived classes (Dog and Cat in this case) that extend the abstract class.
Note that an abstract method does not have a body; it only declares the method signature. Any class that inherits from an abstract class must implement all abstract methods defined in the parent class, or else it will also be considered abstract.
You cannot create an instance of an abstract class. Instead, you create instances of the derived classes (Dog and Cat in this case) that extend the abstract class.
How abstract class work in real time : Upload Images
<?php
abstract class ImageUploader {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
abstract public function uploadImage($image);
}
class ConcreteUploader extends ImageUploader {
public function uploadImage($image) {
$targetDirectory = 'uploads/';
$targetFileName = $targetDirectory . basename($image['name']);
if (move_uploaded_file($image['tmp_name'], $targetFileName)) {
$query = "INSERT INTO images (file_name) VALUES (:file_name)";
$statement = $this->pdo->prepare($query);
$statement->bindValue(':file_name', $targetFileName);
$statement->execute();
return $this->pdo->lastInsertId();
} else {
return false;
}
}
}
// Assuming you already have a PDO connection established
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");
$uploader = new ConcreteUploader($pdo);
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
$imageId = $uploader->uploadImage($image);
if ($imageId !== false) {
echo "Image uploaded successfully. Image ID: " . $imageId;
} else {
echo "Image upload failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Example</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
</body>
</html>
The script begins with the definition of an abstract class ImageUploader. This class has a protected property "$pdo" to store a PDO (PHP Data Objects) instance, which represents a connection to a database.
The constructor of ImageUploader takes a PDO object as a parameter and assigns it to the "$pdo" property.
The ImageUploader class declares an abstract method "uploadImage($image)". This method is meant to be implemented in concrete subclasses and is responsible for handling the actual upload process.
The script then defines a concrete subclass called ConcreteUploader that extends the ImageUploader class. This subclass implements the "uploadImage($image)" method.
The uploadImage($image) method in ConcreteUploader takes an $image parameter, which is expected to be an associative array representing the uploaded image file. It performs the following steps:
- Defines a target directory (upload/) where the image file will be stored.
- Generates a target file name by appending the original file name to the target directory.
- Moves the temporary uploaded file to the target directory using move_uploaded_file(). If the move operation is successful, the method proceeds to insert the file name into a database table called images.
- Creates a SQL query with a prepared statement to insert the file name into the images table.
- Binds the :file_name parameter in the query to the target file name.
- Executes the prepared statement.
- If the execution is successful, the method returns the last inserted ID from the database using $this->pdo->lastInsertId(). Otherwise, it returns false.
- The code establishes a PDO database connection to a MySQL database using the PDO class constructor. The connection details include the host (localhost), database name (phptutorial), username (root), and password ("").
An instance of the ConcreteUploader class is created, passing the PDO connection as a parameter.
The code checks if an uploaded file named image exists in the "$_FILES" superglobal array. If so, it assigns the uploaded file information to the "$image" variable.
The "$uploader" instance's "uploadImage($image)" method is called with the uploaded image as an argument.
If the "uploadImage()" method returns a non-false value (indicating a successful upload), the script displays a success message with the image ID. Otherwise, it displays a failure message.
The remaining part of the code is an HTML form that provides an interface for users to select an image file and submit it for upload. The form uses the POST method and has an enctype attribute set to "multipart/form-data" to handle file uploads correctly.
In summary, this code sets up a basic image upload functionality using PHP and MySQL. It defines an abstract class for image uploading, provides a concrete implementation, establishes a database connection, handles the file upload process, and displays the appropriate messages based on the upload result. The accompanying HTML form allows users to select and submit an image file for upload.