make()方法在Laravel中做了什么?

时间:2017-05-22 23:36:49

标签: laravel methods

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

但我仍然对make()方法究竟是做什么感到困惑。我知道create()方法使用make()方法,然后将它们持久存储到数据库中,make()方法只是暂时将它保存在php tinker中吗?对不起,我是Laravel noob。我想弄清楚这些功能。谢谢! :)

2 个答案:

答案 0 :(得分:5)

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

E.g。

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

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

E.g。 Mailer类的实例将自动注入此处。

namespace App\Services;

use \Illuminate\Mail\Mailer;

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

答案 1 :(得分:0)

我最近发现,当您使用make()时,您正在安装该类,并且可以访问该类或模型的方法,这对于Test并验证您是否正在获取所需的内容很有用。示例: 用户模型

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

测试用户

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'
     }
}

另一方面,如果您使用“创建”会由于创建用户而产生错误

相关问题