私は世界的に使用されるメソッドを含むクラスを持ち、そしてクラス拡張することによって、それらを使用しています: 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回実行しないようにするにはどうすればよいですか?
この投稿を確認することができ、このsingleton reference
を見てみることができます。この
のようにそれを使用します。http: //stackoverflow.com/questions/23160509/check-whether-instance-of-a-class-exists-if-not-create-an-instance –
あなたのAppクラスはdbにアクセスすべきではありません。モデルだけがそれを行うべきです.. –
また、Dependency Injectionについて見てみましょう:http://stackoverflow.com/questions/130794/what-is-dependency-injection –