php - 在 Laravel 5 中调用模型中的方法

标签 php laravel laravel-5.1

我创建了一个名为 Hangman 的模型。在 Controller 内部,我在数据库中插入一行,如下所示

$hangman = new Hangman();
$hangman->word = 'exampleWord';
$hangman->lives = 3;
$hangman->save();

到目前为止一切顺利。

我有两个问题:

1)在 Controller 中不断插入东西是最佳实践吗?

我假设不是,所以我在模型中创建了这个方法,我认为从 Controller 调用它会更干净

public function insert($word, $lives)
{
    $hangman = new Hangman();
    $hangman->word = $word;
    $hangman->lives = $lives;
    $hangman->save();

    return $hangman;
}

所以,我真正的问题(假设问题 1 是否定的)是:

2)我如何从 Controller 调用这个方法?

这不起作用

 \App\Hangman::insert('exampleword', 4);

命名空间正确。

我知道这是非常基本的,谢谢大家

最佳答案

没有人能正确回答你的第一个问题,因为这是个人喜好的问题,人们有不同的看法。将其放入模型中可能是一个好主意,就像将其放入存储库中一样。在正确的应用程序中,将其放在 Controller 中可能是值得的,而其他系统可能更喜欢其他解决方案。

至于你的第二个问题:由于你处于 Hangman 模型中,你应该将自引用调用以及方法本身设为静态。

public static function insert($word, $lives)
{
    $hangman = new static;
    $hangman->word = $word;
    $hangman->lives = $lives;
    $hangman->save();

    return $hangman;
}

这应该足够了。您还可以节省几行:

public static function insert($word, $lives)
{
    return static::create(compact('word', 'lives'));
}

关于php - 在 Laravel 5 中调用模型中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32612149/

相关文章:

PHP|MySql - 无法插入包含撇号的文本

php - 登录页面传递 $_SESSION

php - money_format() 选项

laravel - 如何在已编译的 View 文件中执行 javascript(使用 View::render 方法)

拉拉维尔 5 : How to create a router model binding on multiple parameters

javascript - 我必须使用 ajax 将数据值传递给 Controller

php - mysql "or"查询操作的顺序

javascript - 仅当选择相应的单选按钮时才显示管理员的详细信息?

php - 重定向回自定义请求类 : Laravel 5 中的错误和输入

laravel - 使用 Laravel 5.1 授权方法时如何返回自定义 403 异常