我无法使我的存储库正常工作,当我尝试获取整个文档列表时,它什么也不返回
这是我的DocumentRepository
<?php
namespace App\Repositories\Document;
interface DocumentRepository
{
public function getall();
public function getById($id);
public function create(array $attributes);
public function update ($id, array $attributes);
public function delete ($id);
}
这是功能
<?php
namespace App\Repositories\Document;
class EloquentDocument implements DocumentRepository
{
private $model;
public function __construct(Document $model)
{
$this->model = $model;
}
public function getall()
{
return $this->model->all();
}
public function getById($id)
{
return $this->findById($id);
}
public function create(array $attributes)
{
return $this->model->create($attributes);
}
public function delete($id)
{
$this->getById($id)->delete();
return true;
}
public function update($id array $attributes)
{
$document = $this->model->findOrFail($id);
$document->update($attribute);
return $document;
}
}
这是控制器
<?php
namespace App\Http\Controllers;
use App\Repositories\Document;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class DocumentController extends Controller
{
/**
* @var DocumentRepository
*/
private $document;
/**
* TodoController constructor.
*/
public function __construct(DocumentController $document)
{
$this->document = $document;
}
public function getalldocuments()
{
return $this->document->getAll();
}
}
为您提供信息,我的Documents表/模型中有两行数据,因此我只想通过简单地返回就可以得到这两行数据,但是在我的情况下,它只是不返回任何内容。 这是路线
Route::get('/documents', 'DocumentController@getalldocuments');
这是网站AppAppProviders.php中的注册部分
public function register()
{
$this->app->singleton(DocumentRepository::class, EloquentDocument::class);
}
答案 0 :(得分:1)
您正在键入提示DocumentController
,而不是实际的存储库。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\Document\DocumentRepository;
class DocumentController extends Controller
{
/**
* @var DocumentRepository
*/
private $document;
public function __construct(DocumentRepository $document)
{
$this->document = $document;
}
public function getalldocuments()
{
return $this->document->getAll();
}
}
现在,假设您已正确绑定接口以解析到已实现的文档存储库,则此方法应该可以正常工作。
有关如何将接口绑定到实现的更多信息,请阅读:https://laravel.com/docs/5.7/container#binding-interfaces-to-implementations
编辑:您的存储库界面中存在一些语法问题。您缺少功能:
<?php
namespace App\Repositories\Document;
interface DocumentRepository
{
public function getall();
public function getById($id);
public function create(array $attributes);
public function update($id, array $attributes);
public function delete($id);
}
编辑2:您的绑定正确。但是,我注意到您没有将App\Document
模型正确地绑定到实现。
<?php
namespace App\Repositories\Document;
use App\Document;
class EloquentDocument implements DocumentRepository
{
private $model;
public function __construct(Document $model)
{
$this->model = $model;
}
//
//
//
}
您需要在顶部添加正确的use语句。假设您的文档模型位于App\Document
中,则此方法应该有效。