Laravel 5.1 > use @inject within view to display content

994 views Asked by At

I´m working on a small Web-Application which will be having a private messaging system. While a user is signed in his received or written messages will be displayed in a toolbar area inside a dropdown menu. Nothing new :-)

The toolbar will be displayed most of the time while a user is travelling through the page. So instead of injecting the inbox implementation into each controller which might be called through routes.php I´m thinking about using the new blade function @inject.

This would look like this (abstracted)

  1. Toolbar view calls ControllerMethod via @inject
  2. ControllerMethod calls injected InterfaceMethod (constructor based Injection)
  3. Service Container serves Implementation
  4. ImplementationMethod returns inbox

But I´m not sure if this is a nice design pattern because I´m relatively new to dependency injection in general. I´d appreciate some thaughts.

1

There are 1 answers

1
Seer On

There are 2 things here that are wrong to me.

1) Laravel's @Inject view directive does not actually do any sort of "Dependency Injection", despite it's name suggesting so. It is in fact using service location, a pattern which is widely considered anti-pattern.

Basically, via @Inject, the view has access to anything in the container. It can get anything it wants. It doesn't get told what it should have. That's the principle difference between dependency injection and service location.

2) Injecting services into the view directly will undoubtedly mean that you are adding more complexity to your application because you're added more places where services can be injected into your templates. While it may make things quicker and simpler looking short-term, long-term it will make things more difficult to work with.

3) How will you test how you fetch and control data if that's happening in your view? You'd likely have to use functional testing, which, while not a bad thing to be doing, is still not going to be as useful as unit testing for something like this.

I'd recommend sticking to how things are usually done in regards to DI, and actually use DI.