2016-12-22 8 views
0

私は世界的に使用されるメソッドを含むクラスを持ち、そしてクラス拡張することによって、それらを使用しています: PHP:拡張クラスの複数のインスタンスを防ぐ方法

core.phpの

App.php

final class App extends Core { 

    // The app class handles routing and basically runs the show 

} 
abstract class Core { 

    public function __construct() { // Here we bring in other classes we use throughout the app 
    $this->Db = new Db($this); 
    $this->Mail = new Mail($this); 
    } 

    // Then we define multiple methods used throughout the app 

    public function settings($type) { 
    // You see this used by the model below 
    } 

} 

のindex.php

$App = new App(); // This fires up the app and allows us to use everything in Core.php 

これまではすべてが素晴らしいです。すべてがサイト全体で$Appから処理されたからです。しかし、私のMVC構造内では、モデルはデータベースからデータを引き出すだけでなく、Coreに含まれる他の設定をすべて取得する必要があります。モデルによって$Appクラス全体を使用する必要はありませんが、Coreが必要です。

MyModel.php

class MyModel extends Core { 

    public function welcome() { 
    return 'Welcome to '.$this->settings('site_name'); 
    } 

} 

MyModel.php一度遊びに来て、Coreコンストラクタは、第二回実行されます。 Coreコンストラクタを2回実行しないようにするにはどうすればよいですか?

+0

この投稿を確認することができ、このsingleton reference
を見てみることができます。この

class MyModel extends Core { public function welcome() { $_core = Core::instance; // get the present working instance return 'Welcome to '.$_core->settings('site_name'); } } 

のようにそれを使用します。http: //stackoverflow.com/questions/23160509/check-whether-instance-of-a-class-exists-if-not-create-an-instance –

+0

あなたのAppクラスはdbにアクセスすべきではありません。モデルだけがそれを行うべきです.. –

+0

また、Dependency Injectionについて見てみましょう:http://stackoverflow.com/questions/130794/what-is-dependency-injection –

答えて

1

coreクラスの静的インスタンスを使用して再利用することができます。モデルクラスで

abstract class Core { 
    public static $instance; //create a static instance 

    public function __construct() { // Here we bring in other classes we use throughout the app 
    $this->Db = new Db($this); 
    $this->Mail = new Mail($this); 
    self::$instance = $this; // initialise the instance on load 
    } 

    // Then we define multiple methods used throughout the app 

    public function settings($type) { 
    // You see this used by the model below 
    } 

} 

は、あなたが役立つかもしれないさらに、あなたがこの回答に explain-ci-get-instance

+0

コードにはいくつか問題があります。まずは、必要なだけ多くのクラスをインスタンス化できるので、シングルトンではありません。第二に、自分のインスタンスを作成して保存するためのコンストラクトの使用は、その目的ではないので、悪い方法です。第3に、インスタンスがあるか、インスタンス化する必要があるかどうかをテストする必要があります。そして最後に、本当に悪いコード化されたクラスをリンクしているので、CIは本当に悪いプログラム設計をしています。 –

関連する問題