@
@
@Twitt2017-09-16 14:19:06
Laravel
@Twitt, 2017-09-16 14:19:06

What is the difference between these two code snippets?

Yes, I don’t quite understand the essence of DI, even though I read a lot, but I only understood that an object of another class should be passed to the class constructor, and then the object of the passed class should be passed to the property (well, like here):

class Table {
   public $cup;
  public function __construct(Cup $cup) {
  $this->cup = $cup;
  }
}

And here in Laravel there is this: when a request is passed to an action, it comes as a parameter, and it looks like this:
public function update(RequestUpdatePost $request, $id) {}

However, I tried doing this:
public function update($id) {
  $request = new RequestUpdatePost;

And the result came out the same. What is the fundamental difference with the passages of these two codes?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya Gerasimov, 2017-09-16
@Omashu

The RequestUpdatePost class is inherited from the base Request, it usually describes the rules for request validation, if the request is not valid, errors will fly and such a request will not pass into your method.
An example of how it might look:
448bb42f0716411bb6e8c97640d9513d.jpg

K
Kirill Nesmeyanov, 2017-09-18
@SerafimArts

DI solves the problem of hidden dependencies. Explicit is always better than implicit. And although the second option is not critical, but as soon as the RequestUpdatePost class requires more dependencies, you will have to get them from somewhere.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question