Cynial
Cynial

Reputation: 680

Dependency Injection in Laravel 4 controllers instance all of the objects

I want to make testable code in Laravel 4 controllers. I know DI(Dependency Injection), and I know testable code may look like:

class UsersController extends BaseController
{
    public function __construct(User $user, Notice $notice) 
    {
        $this->user = $user;
        $this->notice = $notice;
    }

    public function getIndex()
    {
        ...
        $this->user
        ...
        $this->notice
        ...
    }

    public function getPage()
    {
        ...
        $this->user
        ...
    }
}

As you can see I injected two objects into the controller.

For getIndex function, it's perfect, I use two object in it.

But please noted that for getPage function, I just use $this->user, I don't need the $this->notice.

However, the $this->notice object was instantiated already, that's really not good.

Is there a better way to not instance all of the objects?

Upvotes: 3

Views: 1024

Answers (2)

Attila Szeremi
Attila Szeremi

Reputation: 5478

Laravel 5 is going to have controller method injection.

http://laravel.com/docs/master/releases#laravel-5.0

Upvotes: 1

Matthieu Napoli
Matthieu Napoli

Reputation: 49573

In most cases I would argue this is premature optimization because seriously the overhead is probably so negligible you are just wasting your time.

If this is a performance issue in your application, then you have the following solutions:

  • lazy injection. I don't know if Laravel DI container offers this feature, but the idea is to inject a Proxy that will load the service lazily. If the service is not used, it's not loaded.
  • separate controllers. You can split your controller in two so that you only inject the services you really use. Sometimes the fact that some dependencies are not used is a sign that the class/controller does too many things, so splitting it is anyway a good thing.

But you should probably not care about creating an injecting an object you don't use, because you will only save 0.00001 second and nobody will see the difference.

Upvotes: 5

Related Questions