Sunday, 30 April 2023

Three ways to create an instance of class in Laravel


interface SomeInterface {
public function doSomething();
}

class SomeImplementation implements SomeInterface {
public function doSomething() {
echo "Did something!\n";
}
}

1. Using 'bind'

- to register ad binding with service container, the container resolve an instance of class, allow to manage class dependencies and customize the instantiation process

// Bind the interface to an implementation in the service container
$this->app->bind(SomeInterface::class, SomeImplementation::class);

2. Using 'resolve' 

- to resolve an instance from the container, the container resolve an instance of class, allow easily access and use object

// Resolve an instance of the implementation from the container
$implementation = resolve(SomeInterface::class);
// or
$implementation = resolve(SomeImplementation::class);
// using
$implementation->doSomething(); // Output: "Did something!"

3. Using 'new'

-  to create a new instance directly, don't use service container

// Create a new instance of the implementation using the "new" keyword
$implementation = new SomeImplementation();
$implementation->doSomething(); // Output: "Did something!"

 Thank you. 

No comments:

Post a Comment

Golang Advanced Interview Q&A