📅  最后修改于: 2023-12-03 15:17:31.208000             🧑  作者: Mango
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.
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.
You can use the make()
method to create instances of classes in various scenarios. Here are some examples:
$myObject = app()->make('MyClass');
This will create a new instance of MyClass and assign it to $myObject
variable.
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.
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
.
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.