laravel 在模型中包含特征的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23652429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to include traits in the model?
提问by user1692333
I have my own user model which requires some permissions. I created /app/models/Permissions.php
inside which is trait. Now i need to use it in /app/models/MyUser.php
. How to do this in Laravel style?
我有自己的用户模型,需要一些权限。我在/app/models/Permissions.php
里面创建了trait。现在我需要在/app/models/MyUser.php
. 如何在 Laravel 风格中做到这一点?
回答by Andreyco
I would do that this way.
我会这样做。
1.Model
一、型号
<?php namespace Models;
// app/models/MyUser.php
class MyUser extends \Eloquent {
use \Traits\Permissions;
/* ... */
}
2.Create Trait itself
2.创建 Trait 本身
<?php namespace Traits;
// app/traits/Permissions.php
trait Permissions {
/* ... */
}
3.Modify composer.json and add this into classmap
3.修改composer.json,将其加入classmap
"app/traits",
4.In order Laravel could autoload traits you need to dump autoload file and generate new one
4.为了让 Laravel 可以自动加载特性,你需要转储自动加载文件并生成新的
php artisan dump
回答by DanyJaibo
Thank you for the example Andreyco.
谢谢你的例子 Andreyco。
To complement this helps to add a function to the model itself. For example, this would be entered in the Trait. In step 2
作为补充,这有助于向模型本身添加一个功能。例如,这将被输入到 Trait 中。在步骤 2
public function scopeGetMyFunction($query, Request $request)
{
//more code....
$query->get();
}
and so we can use it as part of the Model on the controller.
因此我们可以将其用作控制器上模型的一部分。
public function index(Request $request)
{
$models = \App\Models\User::getMyFunction($request);
return $models;
}