2017-08-08 36 views
0

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

到目前为止,我试图用接口和抽象类来实现它,但它似乎不工作。我希望我的所有服务类都是单身人士,并且我通过保护回弹函数来达到此目的(在某种程度上)。我如何执行此操作?

+1

_I希望我的所有服务类都是单身... _非常糟糕/不明智的想法... –

+0

使用带有受保护变量的静态方法? – MacBooc

+0

@bub这是为什么? –

回答

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); 
+0

我只使用那种模式。不过,我正在寻找一种强制模式本身的方法,以便只能编写该模式的服务。你有什么主意吗? –

+0

你知道容器吗?我会添加一个很好的方式来完成它 –

+0

非常感谢,看起来很有希望,很像我希望的。 –

1

您可以通过抛出异常迫使它?

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 
    } 
} 

但是有人反对说:使用它的人可能会访问你的方法/代码,只能改变它。