S
S
Sergey Alekseev2018-01-29 13:44:25
Laravel
Sergey Alekseev, 2018-01-29 13:44:25

Php Laravel, why give contract to class constructor?

I'm studying laravel->contracts and the following question arose:

<?php

namespace App\Orders;

use Illuminate\Contracts\Cache\Repository as Cache;

class Repository
{
    /**
     * Экземпляр кэша.
     */
    protected $cache;

    /**
     * Создание нового экземпляра репозитория.
     *
     * @param  Cache  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }
}

Why do we need to pass the contract to the constructor, because we need to implement it? Or what I don't understand. Or show an article where it is told.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mykola Ivashchuk, 2018-01-29
@mykolaim

Google dependency injection laravel.

J
JhaoDa, 2018-01-29
@JhaoDa

Try reading the documentation .

S
Stanislav Pochepko, 2018-01-29
@DJZT

The contract implies that it has one main released class. But we can also change it.
For example, with the mysql database, the main one, if it is registered in the config. There are also other database drivers working on a contract basis. Mail, cache, repositories and much more work the same

P
PashaNedved, 2018-01-30
@PashaNedved

If you had to implement a contract, then it would be indicated in the class declaration, for example:

class Repository implements RepositoryInterface
или
class Repository extends AbstractRepository

In your example, the Repository class does not implement any contracts. And in the constructor, a ready-made implementation of the contract (that is, an interface) is connected.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question