2 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
我想知道 User::class 叫什么
一個(gè)完整的名稱是類名解析。它結(jié)合了 PHP 解析運(yùn)算符:: 和class 關(guān)鍵字。它不是 Laravel 語(yǔ)法糖,而是 PHP 語(yǔ)法糖。
在所有情況下,它都會(huì)返回類的完全限定名稱,該名稱只是一個(gè)包含類文件的絕對(duì)/相對(duì)路徑的字符串 - 取決于使用它的文件/類的命名空間。
來(lái)自PHP 手冊(cè)
... 使用 ClassName::class 獲取類 ClassName 的完全限定名稱
另一方面,從你提到的 Laravel 用例
public function user()
{
return $this->belongsTo(User::class);
}
Laravel Eloquent 方法belongsTo()和所有類似的方法都指定要傳遞的參數(shù)是字符串。這些方法解析字符串參數(shù)以定位模型的類定義。
來(lái)自Laravel 文檔
傳遞給該hasOne方法的第一個(gè)參數(shù)是相關(guān)模型的名稱。
因此使用
return $this->belongsTo('\App\User');
或者
return $this->belongsTo(User::class);
在語(yǔ)法上是等價(jià)的。這意味著方法定義完全相同,并且沒有參數(shù)類型檢查,因?yàn)閮蓚€(gè)參數(shù)都是字符串。
所以我喜歡 Laravel “只知道”當(dāng)你使用語(yǔ)法糖時(shí)模型在哪里。
是的,它只知道。但這真的很簡(jiǎn)單。它使用 Eloquent 方法的字符串參數(shù)(現(xiàn)在我們知道無(wú)論語(yǔ)法如何,它都是一個(gè)字符串)和當(dāng)前類提供的 Namespace 來(lái)定位模型定義。
例如這個(gè)類定義
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
相當(dāng)于
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne(Phone::class);
}
}
也相當(dāng)于
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne(App\Phone::class);
}
}
您會(huì)注意到第一個(gè)和第三個(gè)示例不需要該namespace指令,因?yàn)樗鼈兪褂玫氖墙^對(duì)路徑名。

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
實(shí)際上 Laravel 并不知道模型在哪里
如果這個(gè)例子有效:
public function user()
{
return $this->belongsTo(User::class);
}
這是因?yàn)槟P涂赡芪挥谕晃募A或命名空間中,否則您可能應(yīng)該像這樣從其他命名空間導(dǎo)入所需的模型。
//At the top of the file you will import the class
use Maybe\Another\Folder\Namespace\OtherObject;
public function user()
{
return $this->belongsTo(OtherObject::class);
}
如果您不想“導(dǎo)入”對(duì)象,您應(yīng)該像這樣使用類的完整路徑。
public function user()
{
return $this->belongsTo(App\OtherFolder\OtherObject::class);
}
總之,laravel 不知道在哪里查找類定義,但是如果您在參數(shù)中傳遞一個(gè)實(shí)例,該實(shí)例將為服務(wù)容器解析,但這是另一個(gè)與模型綁定更相關(guān)的主題
public function method(MyObject $instance)
{
//Laravel will try to automatically generate an instance of $instance
}
- 2 回答
- 0 關(guān)注
- 403 瀏覽
添加回答
舉報(bào)