2017-08-08 14 views
0

PHPでクラスにコンストラクタをデザインパターンの一部として保護させることが可能かどうか疑問に思っています。PHPで保護されたコンストラクタを作成する

これまでインターフェイスと抽象クラスで実装しようとしましたが、動作しないようです。私はすべてのサービスクラスをシングルトンにしたいと思います。カウンタートラクターを保護してこれを(ある程度まで)達成します。これをどのように強制できますか?

+1

_私はすべてのサービスクラスをシングルトンにしたい... _非常に悪い/賢明ではない考え... –

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

しかし、そこでは:それを使用する人はおそらくあなたのメソッド/コードにアクセスでき、それを変更することができます。

関連する問題