PHP命名空间清除使用声明(PHP Namespaces Override Use Statemen

2019-10-20 09:45发布

谁能告诉我,如果有可能重写USE语句?

我的例子是具有MVC设置,其中有核心代码重写与扩展核心版本定制版本每个控制器/模型的能力。

我所面临的问题是,我的核心控制器具有use语句告诉它使用核心模式,所以如果我扩展模型,我不知道如何告诉它使用自定义的模型,而不是核心的一个

我能明显更新核心控制器使用语句来指向自定义的,但核心代码共享,所以自定义版本可能无法使用这个核心的核心的其他网站存在

使用语句显然是文件级所以我猜这是不可能的,但我希望有任何事情我不知道,或者一个解决方法

核心控制器

namespace Core;

use Core\Model\Example as ExampleModel;

class ExampleController {

    public function output() {
        $model = new ExampleModel;
        $model->test();
    }

}

核心模型

namespace Core;

class ExampleModel() {

    public function test() {
        echo 'This is the core test';
    }

}

自定义控制器

namespace Custom;

use Custom\Controller\Example as Base,
    Custom\Model\Example as ExampleModel;

class ExampleController extends Base {

    //Inherits the output() method

}

定制型号

namespace Custom;

use Core\Model\Example as Base;

class ExampleModel extends Base {

    public function test() {
        echo 'This is the custom test';
    }

}

所以,有了这个例子,是有可能对我来说,在不修改核心代码都创建一个使用自定义模式输出“这是自定义测试”,因此定制控制的实例?

但愿我要问是有道理的

谢谢

Answer 1:

我不太确定我明白你的问题,但答案应该是不言而喻的:如果你的自订模式的核心模型扩展,你可以简单地从自定义类扩展另一个类
如果你正在编写的代码,依赖于核心类存在的一个孩子,那么孩子上课成为项目的一个重要组成部分。 如果你不能改变核心本身,添加类的依赖。 就这么简单。

添加继承的第二层不用担心你,这是非常普遍这样做。 像这样的东西是完全可以预见,可靠:

namespace Core;
class Model
{
    public function coreTest()
    {
        return 'from the core';
    }
}
namespace Custom;
use Core\Model;
class CustomModel extends Model
{
    public function customTest()
    {
        return 'from the custom model';
    }
}
//finally
namespace Project;
use Custom\CustomModel;
class ProjectModel extends CustomModel
{
    public function test()
    {
        return array(
            $this->coreTest(),
            $this->customTest(),
            'From the project'
        );
    }
}
$test = new ProjectModel();
echo implode(PHP_EOL, $test->test());

但如果你想有一个给定的类从另一个类扩展的基础上,是否存在这个类,你正在寻找有条件的进口
一个简单的use声明在编译时计算,所以没有办法可以使用if检查到你从哪个扩展类之间切换。

有,然而哈克变通,但我不会依赖它。 检查是否给定的类存在( 无自动加载 ),和一个别名设置为不类。

if (!class_exists('\\Custom\\Model', false))
    class_alias('\\Core\\Model', 'Base');
else
    class_alias('\\Custom\\Model', 'Base');
class CustomModel extends Base
{}

但实际上:不沿着这条路走下去。 确保您的代码将工作,但如果你再靠一种方法可用,在自定义类的定义,但该类失踪,那么你的代码将失败...可怕。

有条件进口详细说明:

为什么要使用类alisases?



文章来源: PHP Namespaces Override Use Statement