php - 仅在存在时才实现接口?
问题描述
我试图找到一种仅在此接口可用时才实现接口的方法。
有问题的接口是
PrestaShop\PrestaShop\Core\Module\WidgetInterface
来自 Prestashop。它在一个模块中使用。
问题是,为了兼容多个版本的 Prestashop,代码必须处理WidgetInterface
不存在的情况。
我正在考虑测试接口的存在并在之后导入它,如下所示:
if (interface_exists('PrestaShop\PrestaShop\Core\Module\WidgetInterface')) {
use PrestaShop\PrestaShop\Core\Module\WidgetInterface
} else {
interface WidgetInterface {}
}
但当然,不可能use
在 if 语句中使用。
然后我尝试做一些尝试/捕捉,但这是同样的问题(太糟糕了,它不是 Python)。
implements WidgetInterface
仅在可用时我该怎么做?
解决方案
您不能像您说的那样动态地实现接口,但是您可以编写自己的接口,并且只有require
在另一个接口不存在时才可以。
即:您的界面将类似于widget_interface.php
,或者您想调用的任何名称,只要它不符合 PSR-0/4 或以您通常执行的任何方式自动加载。
<?php
namespace PrestaShop\PrestaShop\Core\Module;
/**
* This is the replacement interface, using the same namespace as the Prestashop one
*/
interface WidgetInterface
{
}
然后,在您的课堂上,您可以执行以下操作:
<?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
{
}
仅当 Prestashop 不存在时才会加载您的替换界面。