A
A
Andrey Boychenko2019-07-28 13:48:24
Laravel
Andrey Boychenko, 2019-07-28 13:48:24

Laravel 2 ways, write the same thing?

Good afternoon! Guys, tell me what's the difference? and in what situation, which method is preferable to use, is there any difference at all?
Option 1

class ControllerNomenclature extends Controller
{
    private $products;

    public function __construct(ModelProducts $products)
    {
        parent::__construct();
        $this->products = $products;
    }
    
    public function index()
    {
        return $this->products->getProducts();
    }
}

Option 2
class ControllerNomenclature extends Controller
{
    public function index(ModelProducts $products)
    {
        return $this->products->getProducts();
    }
}

As far as I understand, in the first case, when initializing the object, I will be obliged to pass parameters to it otherwise - an error. And in the second case, I will be required to pass parameters to the index. But still, I can calmly initialize the object.
What other fundamental difference is there? In what cases to use one or another approach, perhaps there are specific recommendations?
Thanks a lot for your answers! It hurts, I really want to turn from a housewife into at least a junior php)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Arman, 2019-07-28
@Arik

It seems like:
1. All methods / actions depend on this data and there will be requests or something else
2. Only index depends on this data and only for it there will be a request
in the lara there is no init method?)

K
Konstantin B., 2019-07-28
@Kostik_1993

Everything that the guys above write is all wrong. The fundamental difference is that already received objects are automatically passed to different methods, for index it is a collection, and one class object is passed to show create delete edit update methods. That is, you do not need to execute a request to receive data, they will already be transferred automatically when using the route model binding
In the first case, you will simply have an object without data transferred, the brewers will have to do it themselves in the method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question