鍍金池/ 問答/PHP/ laravel repository 求解?

laravel repository 求解?

假設(shè):通過配置文件可以切換數(shù)據(jù)存儲驅(qū)動,比如數(shù)據(jù)存放在 mysql,然后修改配置文件變?yōu)?redis。
目前我的偽代碼如下:

1:建立一個接口

<?php

namespace App\Repositories\Interfaces;

Interface CategoryInterface
{
    public function getAll();

    public function setData();
}

2:建立兩個 Repository,分別對應(yīng)mysql,redis數(shù)據(jù)庫操作。

<?php

namespace App\Repositories\Implement;

use App\Repositories\Interfaces\CategoryInterface;

class CategoryMysqlRepository implements CategoryInterface
{
    public function getAll()
    {
        // TODO: Implement getAll() method.
    }

    public function setData()
    {
        // TODO: Implement setData() method.
    }

}
<?php

namespace App\Repositories\Implement;

use App\Repositories\Interfaces\CategoryInterface;

class CategoryRedisRepository implements CategoryInterface
{
    public function getAll()
    {
        // TODO: Implement getAll() method.
    }

    public function setData()
    {
        // TODO: Implement setData() method.
    }

}

3:進(jìn)行綁定

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Repositories\Interfaces\CategoryInterface',
            'App\Repositories\Implement\CategoryMysqlRepository');
    }
}

如何更改綁定方式,達(dá)到上述目的。謝謝。

回答
編輯回答
只愛你

通過讀取數(shù)據(jù)庫驅(qū)動來動態(tài)綁定,比如

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 假設(shè)key 為 database.driver, 值可能是 redis/mysql
        $dbDriver = ucfirst(config('database.driver')); 

        $this->app->bind('App\Repositories\Interfaces\CategoryInterface',
            "App\Repositories\Implement\Category{$dbDriver}Repository");
    }
2018年8月22日 11:17