【问题标题】:Force protected constructor in PHPPHP中的强制保护构造函数
【发布时间】:2018-01-16 05:15:21
【问题描述】:

我想知道是否可以在 PHP 中强制一个类将其构造函数作为设计模式的一部分进行保护。

到目前为止,我已经尝试使用接口和抽象类来实现它,但它似乎不起作用。我希望我的所有服务类都是单例,我通过使 counstructor 受到保护来实现这一点(在某种程度上)。我该如何执行?

【问题讨论】:

  • 我希望我的所有服务类都是单例... 非常糟糕/不明智的想法...
  • 对受保护变量使用静态方法?
  • @bub 为什么会这样?

标签: php constructor interface abstract-class


【解决方案1】:

可以使构造函数受保护。

这里是单例模式的示例:

<?php

class Test {

    private static $instance = null;

    protected function __construct()
    {
    }

    public static function getSingleton()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }
}

// Does work
$test = Test::getSingleton();

// doesn't work
$test = new Test();

对于“服务”,使用依赖注入容器。 作为示例,我使用了一个简单的容器实现,但还有更多。 http://container.thephpleague.com/2.x/getting-started/

<?php

interface ExampleServiceInterface {

}

class ImplementationA implements ExampleServiceInterface {

}

class ImplementationB implements ExampleServiceInterface {

}

$container = new League\Container\Container;

// add a service to the container
$container->share(ExampleServiceInterface::class, function() {
    $yourChoice = new ImplementationA();
    // configure some stuff? etc
    return $yourChoice;
});

// retrieve the service from the container
$service = $container->get(ExampleServiceInterface::class);

// somewhere else, you will get the same instance
$service = $container->get(ExampleServiceInterface::class);

【讨论】:

  • 我正在使用这种模式。但是,我正在寻找一种强制模式本身的方法,以便只能编写该模式的服务。你有什么想法吗?
  • 你知道容器吗?我将添加一个很好的方法来完成它
  • 非常感谢,这看起来很有希望,很像我所希望的。
【解决方案2】:

你可以通过抛出异常来强制它吗?

final class Foo {
   private static $meMyself = null;
   protected function __construct() {

      if(!is_null(Foo::$meMyself)) {
         throw new \Exception("ouch. I'm seeing double");
      }
      // singleton init code
   }
}

但有反对意见:使用它的人可能会访问您的方法/代码并且可以更改它。

【讨论】:

    猜你喜欢
    • 2011-05-02
    • 1970-01-01
    • 2018-02-03
    • 2016-04-07
    • 2021-10-05
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多