Type Hinting Eloquent Models

穿精又带淫゛_ 提交于 2019-12-23 12:44:48

问题


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.

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

To which I passed:

new \App\Model()

And finally the error response of:

instance of App\Model given

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?

Edit for more information:

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 {

回答1:


In your type hint, preface the FQCN with a backslash:

function __construct ($resource, \Illuminate\Database\Eloquent\Model $model, $skip = 0)

Either that, or add the use statement to your class:

use Illuminate\Database\Eloquent\Model;

class MyClass {
    function __construct ($resource, Model $model, $skip = 0) {
        //
    }
}


来源:https://stackoverflow.com/questions/30405924/type-hinting-eloquent-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!