Make an Object from a Class using Laravel IOC Container

Panjeh
2 min readFeb 16, 2021

Before you start this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

Suppose ClassName is a class in the App namespace

\App\Classname is equal to ClassName::class

In a controller you can make an object using Laravel IOC container by resolve() method.

resolve(ClassName::class)orresolve('\App\Classname')

Example:

resolve(UserRepo::class)

Here UserRepo is the class name.

note:

In fact, by ClassName::class , we are passing the full string of the class name with its namespace as the argument to the resolve() method.

Before continue reading the reset of this tutorial, I would like to introduce Laravel Pay Pocket which I have developed it recently.

https://github.com/HPWebdeveloper/laravel-pay-pocket

Usage:

As an example in Repository Pattern approach we put all the repositories in a separate classes inside some methods. Then for calling those methods in a Laravel Controller we should first use resolve() method to make an object from those repositories classes then call the methods on that object.

$userObject = resolve(UserRepo::class)$userObject->customMethod()

Alternative-1:

$object = App::make(ClassName::class)

will make also an object and is the same.

Alternative-2:

We can use simply dependency injection to resolve a class.

Suppose there is a method index() in a controller and you are going to resolve a repository class inside the index method.

Then the dependency injection let us do:

public function index(UserRepo $userObject){}

Alternative-3:

Simply use php features like:

$object = new ClassName();

The difference between the alternatives is that the resolve() will give us more ability to test our controller easily. Stay tuned!

--

--