类型提示雄辩模型 [英] Type Hinting Eloquent Models
问题描述
我正在尝试编写好的代码,其中一部分是类型暗示,以便使工作更容易,并强制期望。
I am trying to write good code, and part of that is type hinting to make it easier for work down the line and to force expectations.
这可能看起来有点不舒服,但更多的是我的概念证明。
This may seem a little contrived, but its more of a proof of concept for me.
我是编写一个类,将一个TSV文件拆分在标签上并插入到我的模型中。在我的构造函数中,我要求:
I am writing a class to take a TSV file split on tabs and insert into my Model. In my constructor I was asking for:
Illuminate\Database\Eloquent\Model
我通过了:
new \App\Model()
最后的错误响应:
instance of App\Model given
显然我做错了,但是我不想强制使用App \Model,我如何一般地要求一个有说服力的模型?
Clearly I have done something wrong, but I do not want to force usage of App\Model, how can I generically ask for an eloquent model?
编辑更多信息
为了使之更清楚,我使用的是Laravel 5,这些模型是通过artisan make:model创建的。构造函数如下:
To make it more clear, I am using Laravel 5, the models are created via artisan make:model. The constructor is as follows:
function __construct ($resource, Illuminate\Database\Eloquent\Model $model, $skip = 0)
而我正在使用的模型(对于我的电影表)是:
And the Model I am using (for my movie table) is:
use Illuminate\Database\Eloquent\Model;
class Movie extends Model {
推荐答案
p>在您的类型提示中,使用反斜杠前缀FQCN:
In your type hint, preface the FQCN with a backslash:
function __construct ($resource, \Illuminate\Database\Eloquent\Model $model, $skip = 0)
或者, code>使用语句到你的班级:
Either that, or add the use
statement to your class:
use Illuminate\Database\Eloquent\Model;
class MyClass {
function __construct ($resource, Model $model, $skip = 0) {
//
}
}
这篇关于类型提示雄辩模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!