How can two classes be extended in PHP using OOP?

As a beginner in OOP, I am currently working on writing a PHP class to establish a connection with an FTP server.

class ftpConnect {
  private $server;
  private $user;
  private $password;

  private $connection_id;
  private $connection_correct = false;

  public function __construct($server, $user = "anonymous", $password = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e6e9e8e9feeae8f2f4c7eae6eeeba9e4e8ea">[email protected]</a>") {

    $this->server   = $server;
    $this->user     = $user;
    $this->password = $password;

    $this->connection_id      = ftp_connect($this->server);
    $this->connection_correct = ftp_login($this->connection_id, $this->user, $this->password);

    if ( (!$this->connection_id) || (!$this->connection_correct) ){
        echo "Error! Could not establish a connection to the FTP server: $this->server";
        var_dump($this->connection_id);
        var_dump($this->connection_correct);
        return false;
    } else {
        echo "Successfully connected to the FTP server: $this->server, User: $this->user";
        $this->connection_correct = true;
        return true;
    }
  }
}

I understand that at this point, the body of the class is not significant. However, my main issue lies in comprehending the concept of OOP.

I decided to incorporate sending emails every time the code runs. To achieve this, I downloaded the PHPMailer Class and extended my class with it:

class ftpConnect extends PHPMailer {...}

I added some variables and methods, and everything worked as expected up to that point.

Then, an idea struck me - why not store everything in a database? Each time the user executes the above code, the relevant information should be stored in the database.

I contemplated editing my ftpConnect class by adding a database connection in the constructor, along with other methods for updating tables. However, considering that the database connection and related functionality may be utilized by other classes in the future, it would be best to implement it in a separate class.

The challenge I am facing is that my "main" ftpConnect class already extends another class, so I cannot extend it with any additional ones.

I am unsure about how to resolve this problem. Perhaps my ftpConnect class is too complex, and I should consider dividing it into multiple smaller classes?

Your assistance would be greatly appreciated.

Answer №1

Firstly, I believe there is a flaw in the design of your class. The constructor should not be performing any tasks; instead, it should solely be used to set the properties. It would be advisable to create a separate method called connect() for the actual task.

In addition, ftpConnect and PHPMailer should never be linked through inheritance as they serve completely different purposes. Familiarize yourself with the concept of Liskov substitution principle, which is part of the SOLID principles.

If your class needs to interact with a database or send emails, it is recommended to use dependency injection rather than extending those classes. This approach, known as dependency injection, facilitates easier unit testing by allowing the use of mock objects for mailers or databases.

To handle mailing, database access, and FTP usage, you would ideally require at least three separate classes (possibly more if mapping operations are involved). Each class should have a single responsibility, following the principle of single responsibility principle.

For further references, consider the following:

  • Guide: Writing Testable Code
  • Google Clean Code Talks

Answer №2

When it comes to software design, the principle of composition over inheritance often holds true. Rather than relying on inheritance to build functionality, you can achieve better results by composing objects together. Here is a discussion on Stack Overflow about this concept: Prefer composition over inheritance? In this case, it would be beneficial to use the mailer object and the database object within your class instead of extending them.

To illustrate this idea, let's consider a simple example using PHP:
class MyClass {
    private $mailer;

    public function __constructor() {
         $this->mailer = new Mailer();
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating Numerous CSV Files using PHP

Here is a code snippet: <?php /* Error display */ error_reporting(E_ALL); ini_set('display_errors', 1); ini_set('memory_limit', '512M'); /* Requires */ require 'conn.php'; /* Param ...

The significance of documenting and optimizing code execution

My coding practice is to always (or at least try to) add comments to my code. However, I have set up my server to delete those comments and extra white space before the final delivery. Should I omit comments from the live system's code (Javascript/php ...

Encountering Internal Server Error during Magento's mass reindexing process

Is there a way to reindex a Magento 1.7.02 version site with over 24,000 products and numerous categories? Whenever I attempt to reindex the product price index in Magento Admin Index Management, it triggers an internal Server Error 500. Upon inspecting t ...

Organize the DateTime values in a DataTable

I am running into an issue with sorting the DateTime field in a DataTable. I am fetching records from my server-side customers table. The problem arises when attempting to sort by clicking on the label of a column that contains DateTime values; the data is ...

Show the most recent image from a folder in real-time

Looking for a solution to automatically display the latest image from a folder without refreshing the page? Check out this code snippet that achieves just that: <?php foreach (glob('/home/pi/camera/*.jpg') as $f) { $list[] = $f; } sort( ...

The phpUnit code coverage analysis for interfaces is not yielding positive results

Currently, I am conducting a whitebox test where the parent class and all interfaces are thoroughly tested. To ensure coverage, I have added the following doc comment: /** * @covers \Pat\Environment\PHP\Autoloader\Psr0<extende ...

Using Selenium to identify and recognize different color patterns

Is it feasible to use Selenium (preferably in combination with PHPUnit Selenium) to detect colors on a webpage? I have banners on my site, and some of them do not reload properly. It's strange because I can access their elements, but all I see on the ...

Contrasting readline and fread/fgets functions in PHP

Throughout my experience, I've consistently relied on the readline function for handling console input. However, recently I stumbled upon the fread and fgets functions and it left me wondering: what sets these two methods apart? // Code example using ...

The security measures for encoding and decoding PHP sessions are of utmost importance

This particular query is an extension of another one, found here. Our team is contemplating the release of a new class that would be responsible for handling the deserialization and serialization of session data stored in a table on a large-scale producti ...

Generating well-structured JSON response to be utilized in highcharts alongside Laravel is crucial for efficient data

In one of my views, I have integrated a highcharts chart and I am trying to load the data via ajax from an API route that returns a JSON response. Here is the API route I created: Route::get('api/v1/data/{id}', function($id) { //Perform som ...

When using SQL Server, Windows Authentication is successful when connecting through Management Studio but not when using Apache

My PHP application built with Codeigniter is attempting to connect to SQL Server 2016 using Windows Authentication. Encountering the following error message: Array ( [0] => Array ( [0] => 28000 [SQLSTATE] => 28000 [1] => 18456 [code] => 1 ...

Changing RSS elements in WordPress

My employer has requested that I include a rel='nofollow' attribute in the WordPress RSS feed on our website. Currently, the RSS feed already contains the rel='nofollow' attribute in all the <a href> tags and is functioning proper ...

Querying MySQL with a large join operation combining multiple values to assist in retrieving the necessary

My query fetches most of the necessary information: SELECT cm.*, companies.company_name, companies.permalink,last_met.*,(cm.total_unique_visitors - last_met.last_UV)/last_met.last_UV * 100 as percent_change FROM calculated_metrics as cm LEFT JOIN comp ...

Identifying session status across all controllers in CodeIgniter may result in an error

After trying the code below to verify if a user is logged in, I encountered an issue when moving it to a server. While it worked fine on localhost, it displayed an error as shown https://i.stack.imgur.com/S3XJO.jpg This snippet below is where I am loading ...

Sending notifications from a PHP server to an Android application using Firebase Cloud Messaging (FCM)

As a novice in PHP, I am attempting to create a program that can send a basic notification (consisting of a title and message) from a localhost using PHP to an Android application through Firebase. While I have successfully sent notifications from FCM to A ...

Can PHP files be rewritten using fwrite without deleting PHP comments?

Within a PHP file, there are some comments included. <?php $test = array( 'LBL_TEXT' => 'text',//test comment 'LBL_FOO' => 'foo' ); I want to change the value of 'LBL_TEXT' (& ...

The variables do not align with the number of parameters specified in the prepared statement

As I work on developing an application, I encounter an issue with the login page where I need to verify if a user exists in the database. Although my code seems correct as I only check for the name, I am facing an error when implementing the prepared state ...

Display a JavaScript dialogue box containing a PHP variable

Is there a way to display the correct JavaScript box when using a While loop in PHP? Here is the code snippet: while($result= mysql_fetch_array($data)){ <tr class="<?php echo $style;?>"> <td><?php echo $result['commis ...

Display the most recent product category exclusively in Laravel 5.8

Within my database, I have three entities: products, categories, and product_category. A single product can be associated with multiple categories, and some of these categories may have a parent category. The desired information on how these entities are r ...

Auto-suggest feature using Jquery for dynamically pulling suggestions from a database table

How can I implement an auto-suggest text field that can fetch usernames from my database? I intend to utilize the autocomplete plugin from Jquery UI for this purpose. My aim is to create a fast and highly secure solution. ...