在非对象上调用成员函数 getPaginate()

Call to a member function getPaginate() on a non-object

我是 laravel framwork 的新手,我正在编写我的第一个网络应用

并出现以下错误

 FatalErrorException in PersonController.php line 26:
Call to a member function getPaginate() on a non-object

这是我的控制器

   <?php

namespace App\Http\Controllers; 
use App\Repositories\PersonRepository;

class PersonController extends Controller
{
    protected  $personRepo ;
    protected  $nbrPerPage = 4 ;


    public  function  _construct(PersonRepository $personRepository)
    {
        $this->personRepo = $personRepository ;
    }
    public function index()
    {
        $persons = $this->personRepo->getPaginate(nbrPerPage);
        $links = $persons->setPath('')->render();

        return view('index', compact('persons', 'links'));
    }

    public function create()
    {

    }


    public function store()
    {

    }


    public function show($id)
    {
        //
    }


    public function edit($id)
    {
        //
    }


    public function update($id)
    {
        //
    }


    public function destroy($id)
    {
        //
    }


}

这是我的存储库 class

<?php
namespace  App\Repositories ;
use App\Person ;
use App\User;


class PersonRepository {

  protected  $person ;
    public function  _construct (Person $person)
    {
        $this->$person = $person  ;
    }


    public  function  getPaginate($n)
    {

        return $this->person-> paginate($n) ;
    }


 }

您正在实例化 Person 模型的一个空实例,然后尝试在您的存储库中对其调用 paginate()。但是,paginate() 意味着在查询构建器对象或 Eloquent 查询上调用。假设您想要 return 对 all 模型的分页结果,您可以完全废弃 $person 属性 以及构造函数,然后只将您的方法更改为:

public  function  getPaginate($n)
{
    return Person::paginate($n) ;
}

我会说,对于这样一个简单的查询,我建议不要完全使用存储库,而只需在控制器中使用 Person::paginate($n),因为 Eloquent 本质上已经作为存储库运行。

除非这些只是问题中的拼写错误,否则您的代码中有很多拼写错误。

导致此特定错误的拼写错误是构造方法的名称应为 __construct(带两个下划线),而不是 _construct(带一个下划线)。

由于构造方法在您的 PersonController 上拼写错误,因此永远不会调用此方法并且永远不会设置 personRepo 属性。由于它从未设置,$persons = $this->personRepo->getPaginate(nbrPerPage); 行试图在 non-object.

上调用 getPaginate()

补充typos/issues我一看就知道:

  • $persons = $this->personRepo->getPaginate(nbrPerPage);
    nbrPerPage 被用作常量。这是不正确的。应该是:
    $persons = $this->personRepo->getPaginate($this->nbrPerPage);
  • PersonRepository 上的构造函数也拼写错误。应该是 __construct(),而不是 _construct.
  • $this->$person = $person ;
    这是在 PersonRepository 的尝试构造中。 $ 需要从 $this->$person 中删除。应该是:
    $this->person = $person;