我试图找到一种方法来实现一个接口,只有当这个接口是可用的。
所讨论的界面是
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 {}
}但是当然,在if语句中使用use是不可能的。
然后我尝试做一些尝试/捕捉,但这是相同的问题(可惜不是Python)。
只有在可用时,我才能对implements WidgetInterface做些什么?
发布于 2019-09-18 16:10:33
您不能像您说的那样动态地实现一个接口,但是您可以编写自己的接口,并且只有当另一个接口不存在时才能编写它。
Ie:您的界面应该类似于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接口不存在时,才会加载替换界面。
发布于 2019-09-19 02:29:28
是的,您不能将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接口继承,或者提供它自己的实现,然后让您的类继承它。
https://stackoverflow.com/questions/57996429
复制相似问题