How to solve the code duplication problem?

5

In Wordpress I'm creating a custom screen in the admin area.

For this I am extending my class customProductsListTable to class WP_List_Table :

class customProductsListTable extends WP_List_Table

I have another class for another custom screen that extends the same class WP_List_Table :

class customReviewsListTable extends WP_List_Table

The problem is that in classes customProductsListTable and customReviewsListTable I have created some methods that are common and do not exist in class WP_List_Table .

Then we have the following scenario:

  • The customReviewsListTable and customProductsListTable classes overwrite some methods of the WP_List_Table class, but the code behaves differently in each class.

  • The customReviewsListTable and customProductsListTable classes have new methods but with the same behavior.

I'm clearly duplicating code in both classes, but we can not inherit PHP in more than one class.

How to solve the code duplication problem?

    
asked by anonymous 09.10.2017 / 13:10

1 answer

4

Create an intermediate class, something like this:

class CustomListTable extends WP_List_Table

In it, overwrite the methods you want and create the new ones that will be common. Then inherit like this:

class CustomProductsListTable extends CustomListTable

class CustomReviewsListTable extends CustomListTable

In these classes you can override and create new methods that are specific to them.

Keep your nomenclature, but note that it differs from that used in WordPress. This is confusing. While it is confusing to all of PHP .

I have the impression that this intermediate class may be abstract, but without seeing the whole context I can not say.

    
09.10.2017 / 13:18