Laravel 中的 make() 方法有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44123610/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:01:36  来源:igfitidea点击:

What does the make() method do in Laravel?

laravelmethods

提问by Simon Suh

In the Laravel documentation, I found the following - https://laravel.com/docs/5.4/container#the-make-method

在 Laravel 文档中,我发现了以下内容 - https://laravel.com/docs/5.4/container#the-make-method

but I am still confused as to what exactly the make() method does. I know the create() method uses the make() method and then persists them into the database, so does make() methods just temporarily save it in php tinker or something? Sorry, I'm Laravel noob. I'm trying to figure out these functions. Thank you! :)

但我仍然对 make() 方法的作用感到困惑。我知道 create() 方法使用 make() 方法,然后将它们持久化到数据库中,那么 make() 方法是否只是将它临时保存在 php tinker 或其他东西中?抱歉,我是 Laravel 菜鸟。我试图弄清楚这些功能。谢谢!:)

回答by fubar

The makemethod will return an instance of the class or interface you request. Where you request to make an interface, Laravel will lookup a binding for that interface to a concrete class.

make方法将返回您请求的类或接口的实例。在您请求创建接口的地方,Laravel 会查找该接口到具体类的绑定。

E.g.

例如

$app->make('App\Services\MyService'); // new \App\Services\MyService.

One advantage to using the makemethod, is that Laravel will automatically inject any dependencies the class may define in it's constructor.

使用该make方法的一个好处是,Laravel 将自动注入该类可能在其构造函数中定义的任何依赖项。

E.g. an instance of the Mailerclass would be automatically injected here.

例如,Mailer类的实例将在这里自动注入。

namespace App\Services;

use \Illuminate\Mail\Mailer;

class MyService
{
    public function __construct(Mailer $mailer) {
        $this->mailer = new Mailer;
    }
}

回答by Mau Web

I discovered recently that when you use make (), you are installing the class and you can access the methods of that class or model, this is a useful for the Test and validate that you are getting what you want Example: User model

我最近发现,当您使用 make() 时,您正在安装该类并且您可以访问该类或模型的方法,这对于测试和验证您是否得到了您想要的东西很有用示例:用户模型

class User extends Authenticatable
{
public function getRouteKeyName ()
???? {
???????? return 'name';
???? }
}

Test user

测试用户

class UserTest extends TestCase
{
  public function route_key_name_is_set_to_name ()
???? {
       $ user = factory (User :: class) -> make ();
       $ this-> assertEquals ('name', $ user-> getRouteKeyName ());
       // When you access the getRouteKeyName method you get the return, that is 'name'
     }
}

On the other hand if you use "create" that would give an error because you are creating a user

另一方面,如果您使用“创建”会产生错误,因为您正在创建一个用户