[英]Non-Static Method should not be called Statically
我正在使用存儲庫模式,並試圖建立模型之間的關系。 當我嘗試運行store()方法(在控制器中)試圖使用user()方法(該方法與Party模型建立關系)時,收到以下錯誤消息:
假設不兼容的上下文中的$ this,則非靜態方法Party :: user()不應靜態調用
我不明白為什么嘗試運行user()關系方法時會收到此錯誤,但是所有其他方法(包括$ this-> party-> all(),$ this-> party-> create( $ data)),就可以了。
以下是相關代碼:
// PartiesController.php
public function __construct(Party $party){
$this->party = $party
}
public function store(){
$data = Input::all();
$user = Sentry::getUser();
$this->party->user()->create($data);
}
// Party.php
class Party extends Eloquent{
public function user(){
return $this->belongsTo('User');
}
}
// User.php
use Cartalyst\Sentry\Users\Eloquent\User as SentryUserModel;
class User extends SentryUserModel implements UserInterface, RemindableInterface {
public function party(){
return $this->hasMany('Party');
}
}
// PartyRepository.php
namespace repositories\Party;
interface PartyRepository{
public function all();
public function findByID($id);
public function create($input);
public function user();
}
// EloquentPartyRepository.php
namespace repositories\Party;
use Party;
class EloquentPartyRepository implements PartyRepository{
public function all(){
return Party::all();
}
public function create($input){
return Party::create($input);
}
public function user(){
return Party::user();
}
}
問題是因為您要在靜態上下文中調用非靜態方法。 您可能已經習慣於了解Laravel進行大量此類操作的方式(例如User::find()
等)。 但是,實際上這些並不是靜態調用(實際上是在后台解析類實例,並在該實例上調用find()
方法)。
在您的情況下,這只是一個普通的靜態方法調用。 PHP將允許這樣做,但事實是您在方法中引用了$this
而PHP不知道如何處理它。 根據定義,靜態方法調用不了解類的任何實例。
我的建議是將Model類的實例注入到存儲庫的構造函數中,如下所示:
//Class: EloquentPartyRepository
public function __construct(Party $party)
{
$this->party = $party;
}
public function user($partyId)
{
return $this->party->find($partyId)->user();
}
您發送給構造函數的Party
實例不應是數據庫中的記錄,而應該只是Party
的空實例(即new Party()
),盡管我相信,如果僅將其添加到構造函數中,則IoC應該能夠利用依賴注入,並為您提供實例。
這里有一個等效的實現,它添加了byId
方法:
//Class: EloquentPartyRepository
public function __construct(Party $party)
{
$this->party = $party;
}
public function byId($partyId)
{
return $this->party->find($partyId);
}
public function user($partyId)
{
if($party = $this->byId($partyId)) {
return $party->user();
}
return null;
}
我已經解決了問題。 感謝@watcher和@deczo的反饋。 兩者都非常有用,並且與此錯誤消息相關。
最后,我只需要更改一行即可。 我在store()
函數中無序地調用了方法。 這是相關的代碼。
// PartiesController.php
public function store(){
$data = Input::all();
$user = Sentry::getUser();
$user->party()->create($data);
}
就我而言,要消除非靜態錯誤並將User
模型正確插入Party
模型中,我只需要進行上述更改。
我參考了http://laravel.com/docs/eloquent/#inserting-related-models以獲取適當的序列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.