Php 仅当存在时实现接口?
我试图找到一种方法来实现一个接口,只有当这个接口可用时 所讨论的接口是Php 仅当存在时实现接口?,php,prestashop,Php,Prestashop,我试图找到一种方法来实现一个接口,只有当这个接口可用时 所讨论的接口是 PrestaShop\PrestaShop\Core\Module\WidgetInterface 从普雷斯塔肖普。它用于一个模块中 问题是,为了与多个版本的Prestashop兼容,代码必须处理WidgetInterface不存在的情况 我在测试接口的存在性并在之后导入它时思考,如下所示: if (interface_exists('PrestaShop\PrestaShop\Core\Module\WidgetInte
PrestaShop\PrestaShop\Core\Module\WidgetInterface
从普雷斯塔肖普。它用于一个模块中
问题是,为了与多个版本的Prestashop兼容,代码必须处理WidgetInterface
不存在的情况
我在测试接口的存在性并在之后导入它时思考,如下所示:
if (interface_exists('PrestaShop\PrestaShop\Core\Module\WidgetInterface')) {
use PrestaShop\PrestaShop\Core\Module\WidgetInterface
} else {
interface WidgetInterface {}
}
当然,在if语句中不可能使用use
然后,我尝试了一些try/catch,但这是同一个问题(可惜它不是Python)
只有在可用的情况下,我才能
实现WidgetInterface
。您不能像您所说的那样动态实现接口,但您可以编写自己的接口,并且只有在另一个接口不存在的情况下,才需要它
Ie:您的接口可能类似于widget\u 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
{
}
True,您不能将use
放入if
块中,而use
仅为类设置别名。它不会尝试加载该类。因此,它可以安全地位于if
块之外
您可以在if
中定义类或接口本身
Symfony是如何处理这个问题的,继承了一个可能不存在的接口:
namespace Symfony\Contracts\EventDispatcher;
use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
if (interface_exists(PsrEventDispatcherInterface::class)) {
interface EventDispatcherInterface extends PsrEventDispatcherInterface
{
public function dispatch($event);
}
} else {
interface EventDispatcherInterface
{
public function dispatch($event);
}
}
就我个人而言,为了保持干净并包含在一个点中,我会像这样定义您自己的接口,该接口继承自PrestaShop
接口(如果可用),或者提供自己的实现,然后让您的类继承自该接口。我想到了反射。是的!我有点迷路了。在这种情况下,我肯定不是唯一一个。。。与其使用,不如尝试在if()中使用。
namespace Symfony\Contracts\EventDispatcher;
use Psr\EventDispatcher\EventDispatcherInterface as PsrEventDispatcherInterface;
if (interface_exists(PsrEventDispatcherInterface::class)) {
interface EventDispatcherInterface extends PsrEventDispatcherInterface
{
public function dispatch($event);
}
} else {
interface EventDispatcherInterface
{
public function dispatch($event);
}
}