有趣的問題。我做了一些修補,但我不知道這是你想要的。但是您可以動態創建存儲庫類所需的Eloquent模型實例。
比方說,你必須存儲在app\Models\User.php
您User
模型類:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//
}
然後,您創建一個抽象基類所有的倉庫類:app\Repositories\BaseRepository.php
。這是您放置存儲庫類的所有常用功能的地方。但不是通過構造函數注入Eloquent實例,而是添加一個名爲getModel()
的方法來動態創建存儲庫的Eloquent模型實例。
<?php
namespace App\Repositories;
use ReflectionClass;
use RuntimeException;
use Illuminate\Support\Str;
abstract class BaseRepository
{
protected $modelNamespace = 'App\\Models\\';
public function getById($id)
{
return $this->getModel()->find($id);
}
public function getModel()
{
$repositoryClassName = (new ReflectionClass($this))->getShortName();
$modelRepositoryClassName = $this->modelNamespace . Str::replaceLast('Repository', '', $repositoryClassName);
if (! class_exists($modelRepositoryClassName)) {
throw new RuntimeException("Class {$modelRepositoryClassName} does not exists.");
}
return new $modelRepositoryClassName;
}
}
現在讓我們假設你想創建一個信息庫用於User
模型,並且這個用戶的庫必須實現以下接口:app\Repositories\UserRepositoryInterface.php
<?php
namespace App\Repositories;
interface UserRepositoryInterface
{
public function getByEmail($email);
}
創建app\Repositories\UserRepository.php
類,並簡單地從BaseRepository
擴展它類。另外不要忘記實施在UserRepositoryInterface
上定義的所有特定實現。
<?php
namespace App\Repositories;
use App\Repositories\BaseRepository;
use App\Repositories\UserRepositoryInterface;
class UserRepository extends BaseRepository implements UserRepositoryInterface
{
public function getByEmail($email)
{
return $this->getModel()->where('email', $email)->firstOrFail();
}
}
這樣你就可以綁定UserRepositoryInterface
它是像這樣實現:
$this->app->bind(\App\Repositories\UserRepositoryInterface::class, \App\Repositories\UserRepository::class);
最後,你可以自由地注入UserRepositoryInterface
到控制器的構造函數或方法。您還可以通過服務容器解決這樣的:
$userRepository = App::make(App\Repositories\UserRepositoryInterface::class);
$userRepository->getByEmail('[email protected]');
當然,這裏有一個問題,以這種方式。存儲庫類應以相關模型啓動,因此InvoiceRepository.php
專用於Invoice.php
模型類。
希望得到這個幫助!
您可以從中得到啓發這個http://meanderingsoul.com/dev/2015/04/dependency-injection-with-inherited-controllers-in-laravel-5 –
或者也許只是從ExampleRepository類中移除構造函數,除非調用父構造函數,否則沒有其他要做的事情。 –
@MateuszDrost我沒有輸入,但還有更多的事情要做。每個存儲庫都有自己的依賴關係(通常只是雄辯模型,因爲我不喜歡濫用外觀)。 – user2430929