Search code examples
phpoopinterface

Implements Interface only if exists?


I'm trying to find a way to implement an Interface only when this Interface is available.

The Interface in question is

PrestaShop\PrestaShop\Core\Module\WidgetInterface

From Prestashop. It's used in a module.

The thing is, in order to be compatible with multiple version of Prestashop, the code must handle the case where WidgetInterface does not exists.

I was thinking in testing the existence of the interface and import it after, like this:

if (interface_exists('PrestaShop\PrestaShop\Core\Module\WidgetInterface')) {
    use PrestaShop\PrestaShop\Core\Module\WidgetInterface
} else {
    interface WidgetInterface {}
}

But of course, it's not possible to use use inside a if statement.

I then tried to do some try/catch, but that's the same issue (too bad it's not Python).

How can I do to implements WidgetInterface only when available?


Solution

  • You can't implement an interface dynamically, like you say, but you can write your own interface and only require it if the other does not exist.

    Ie: your interface would be something like widget_interface.php, or whatever you want to call it, as long as it's not PSR-0/4 compliant, or autoloaded in whatever way you normally do.

    <?php    
    
    namespace PrestaShop\PrestaShop\Core\Module;
    
    /**
     * This is the replacement interface, using the same namespace as the Prestashop one
     */
    interface WidgetInterface
    {
    }
    

    Then, in your class, you can do the following:

    <?php
    
    namespace App;
    
    if (!interface_exists('\PrestaShop\PrestaShop\Core\Module\WidgetInterface')) {
        require __DIR__ . '/path/to/widget_interface.php';
    }
    
    class WhateverClass implements \PrestaShop\PrestaShop\Core\Module\WidgetInterface
    {
    
    }
    

    Your replacement interface will only be loaded if the Prestashop one doesn't exist.