Maison >développement back-end >tutoriel php >classe singleton laravel qui connecte plusieurs bases de données différentes
Lors de la connexion à plusieurs bases de données différentes, vous devez écrire plusieurs connexions. Afin de simplifier l'opération, vous pouvez utiliser cette classe de base. Tant que différentes bases de données établissent des classes correspondantes et héritent de cette classe, vous pouvez utiliser le modèle ORM. pour fonctionner.
<code class="sourceCode php"><span class="kw">class</span> singletonInstance { <span class="kw">protected</span> <span class="kw">static</span> <span class="kw">$instances</span> = <span class="ot">[];</span> <span class="kw">protected</span> <span class="kw">static</span> <span class="kw">$table</span> = <span class="kw">null</span><span class="ot">;</span> <span class="kw">protected</span> <span class="kw">static</span> <span class="kw">$connection</span> = <span class="kw">null</span><span class="ot">;</span> <span class="kw">public</span> <span class="kw">function</span> <span class="fu">__construct</span><span class="ot">()</span> { <span class="kw">if</span><span class="ot">(</span>!<span class="fu">isset</span><span class="ot">(</span><span class="kw">static</span>::<span class="kw">$instances</span><span class="ot">[</span><span class="kw">static</span>::<span class="kw">class</span><span class="ot">]))</span>{ <span class="kw">if</span><span class="ot">(</span><span class="fu">is_null</span><span class="ot">(</span><span class="kw">self</span>::<span class="kw">$table</span><span class="ot">)</span> || <span class="fu">is_null</span><span class="ot">(</span><span class="kw">self</span>::<span class="kw">$connection</span><span class="ot">))</span> { <span class="kw">throw</span> <span class="kw">new</span> \<span class="kw">Exception</span><span class="ot">(</span><span class="st">'not defined property'</span><span class="ot">);</span> } <span class="kw">static</span>::<span class="kw">$instances</span><span class="ot">[</span><span class="kw">static</span>::<span class="kw">class</span><span class="ot">]</span> = <span class="kw">DB</span>::connection<span class="ot">(</span><span class="kw">self</span>::connection<span class="ot">)</span>->table<span class="ot">(</span><span class="kw">self</span>::<span class="kw">$table</span><span class="ot">);</span> } } <span class="kw">public</span> <span class="kw">static</span> <span class="kw">function</span> getDB<span class="ot">()</span> { <span class="kw">return</span> <span class="kw">static</span>::<span class="kw">$instances</span><span class="ot">[</span><span class="kw">static</span>::<span class="kw">class</span><span class="ot">];</span> } }</code>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!