Reputation: 680
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
Reputation: 5478
Laravel 5 is going to have controller method injection.
http://laravel.com/docs/master/releases#laravel-5.0
Upvotes: 1
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:
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