mercredi 13 février 2019

PHP class inheritance problem - using subclasses but staying in original namespace for vendor-specific variations

I’m trying to figure out the best (or any way) how to solve my class inheritance problem. I am developing and maintaining a quite large integration platform that reads multiple csv files from multiple vendors. Unfortunately (because of reasons) the data I’m reading can differ slightly in various kinds from vendor to vendor. But in general the format is mostly our Standard.

So I developed the following class structure:

├── Integrations/
│   ├── Initialization.php
│   ├── Standard/
│   │   ├── Synchronization.php
│   │   ├── Translation.php
│   │   ├── Csv.php
│   │   ├── ...
│   ├── VendorA/
│   │   ├── Synchronization.php
│   │   ├── Translation.php
│   │   ├── Csv.php
│   │   ├── ...
│   ├── VendorB/
│   │   ├── Synchronization.php
│   │   ├── Translation.php
│   │   ├── Csv.php
│   │   ├── …

Because every Vendor class is mostly the same as the Standard equivalent. All Vendor classes inherit from Standard. In the Vendor classes I would override methods if needed.

So I would inherit as following:

  • VendorA\Synchronization extends Standard\Synchronization
  • VendorA\Translation extends Standard\Translation
  • VendorA\Csv extends Standard\Csv
  • VendorB\Synchronization extends Standard\Synchronization
  • VendorB\Translation extends Standard\Translation
  • VendorB\Csv extends Standard\Csv

Initialization.php knows which Vendor will be synchronized and inits either VendorA's or VendorB's Synchronization class and starts the sync() method.

The sync() method creates instances of Translation and Translation can create instances of Csv and so forth…

So here is my problem: I will create instances of Translation inside the sync() method of the Standard class. So I will create an instance of Standard\Translation. But I want to create an instance of the vendor-specific Translation class (e.g. VendorA\Translation). See code below. So

I actually want to stay inside the namespace of the children. The namespace how the class was instantiated.

namespace Integrations\Standard;

class Synchronization
{
    public function sync()
    {
        // …
        $translation = new Translation(); // this will create an Standard\Translation() object and not a vendor-specific Translation
        // …
    }
}

Is there any way to achieve this in a nice way? Maybe without bubbling every classname through my structure? And maybe even keep some IDE-code assistance? I am grateful for any help!

Aucun commentaire:

Enregistrer un commentaire