📜  make() laravel - PHP (1)

📅  最后修改于: 2023-12-03 15:17:31.208000             🧑  作者: Mango

Laravel - Make()

Introduction

In Laravel, make() is a handy method used to create an instance of a class. It allows you to avoid manually constructing objects and to rely on Dependency Injection instead.

Syntax

The syntax of make() method in Laravel is as follows:

app()->make('ClassName');

Here, ClassName represents the name of the class you want to instantiate.

Usage

You can use the make() method to create instances of classes in various scenarios. Here are some examples:

Creating a new object
$myObject = app()->make('MyClass');

This will create a new instance of MyClass and assign it to $myObject variable.

Resolving Dependencies

You can also use make() to resolve dependencies of a class. For example:

class MyController
{
    protected $myService;

    public function __construct(MyService $myService)
    {
        $this->myService = $myService;
    }
}

$app->make('MyController');

In this example, MyController constructor requires an instance of MyService to be injected. When you call make() on MyController, Laravel will resolve MyService and inject it into the controller.

Resolving From Container

Finally, you can also use make() to resolve instances from the container. For example:

interface MyInterface {
  public function myMethod();
}

class MyClass implements MyInterface {
  public function myMethod() {
    echo "Hello World!";
  }
}

$app->bind('MyInterface', 'MyClass');

$myObject = app()->make('MyInterface');

$myObject->myMethod(); // Output: Hello World!

In this example, MyInterface is bound to MyClass using the bind() method. Then, calling make() on 'MyInterface' will resolve an instance of MyClass.

Conclusion

In conclusion, make() is a useful method in Laravel that allows you to instantiate classes and resolve dependencies. It is an important feature of Laravel’s powerful IoC container.