首页 > 后端开发 > php教程 > laravel連接多個不同數據庫的單例類

laravel連接多個不同數據庫的單例類

PHP中文网
发布: 2023-03-11 09:20:02
原创
1228 人浏览过

在連接多個不同數據庫時,需要寫多個連接,爲了簡化該操作,可以使用該基類,不同的數據庫只要建立好相對應的類繼承該類,就可以使用ORM模型進行操作了。

<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>
登录后复制

以上是laravel連接多個不同數據庫的單例類的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板