阻止直接绕过工厂创建类的可能性 [英] Blocking the possibility to create classes directly bypassing a factory

查看:71
本文介绍了阻止直接绕过工厂创建类的可能性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的MVC系统中所有模型的基类中,我创建了一个工厂方法BaseCLass :: getNew(),当通过SomeChildClass :: getNew()调用该方法时,该方法返回所请求的子类的实例.

In a base class for all the models in our MVC system, I created a factory method BaseCLass::getNew() that returns an instance of the requested child class when called via SomeChildClass::getNew().

现在,我正在寻找一种强制程序员使用此工厂的方法.即,通常,我希望直接创建任何类,如下所示:

Now, I'm looking for a way to force the programmer to use this factory. I.e., idially I'd like that any class created directly, like this:

 new SomeChildClass

将在创建时引发异常,并且只有工厂创建的类才可用.

will throw an exception upon creation, and only classes created by the factory will be usable.

有什么想法可以实现吗?

Any ideas how can this be achieved?

我们的代码是用PHP编写的,但是即使您使用其他语言,您的想法也很有价值.

Our code is written in PHP, but good chance that your idea will be valuable even if you think on a different language.

我不能将我的构造函数设为私有,因为我继承的类中的框架构造函数是公共的,而php不允许这样做.

edit: I cannot make my constructor private, as the framework constructor in the class that I inherit is public, and php would not allow me this.

推荐答案

通过使该类具有私有的构造函数.

By making the class have a private constructor.

class Base {
    private static $constructorToken = null;

    protected static function getConstructorToken() {
        if (self::$constructorToken === null) {
            self::$constructorToken = new stdClass;
        }

        return self::$constructorToken;
    }
}

class Derived extends Base {
    public function __construct($token) {
        if ($token !== parent::getConstructorToken()) {
            die ("Attempted to construct manually");
        }
    }

    public static function makeMeOne() {
        return new Derived(parent::getConstructorToken());
    }
}

此解决方案通过将魔术密码"对象存储在仅派生类可以访问的基类上,从而利用了stdClass的对象相等性规则.您可以调整它的味道.

This solution takes advantage of the object equality rules for stdClass by storing a "magic password" object on the base class which only derived classes can access. You can tweak it to taste.

我不会像debug_backtrace那样称其为"可怕",但是我仍然觉得事情应该以不同的方式进行.

I wouldn't call it horrible like the debug_backtrace idea, but still I have the impression that things should be done differently.

这篇关于阻止直接绕过工厂创建类的可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆