K
K
Konstantin Eliseev2019-08-01 10:34:15
Laravel
Konstantin Eliseev, 2019-08-01 10:34:15

How can you automatically create an object in Laravel?

Laravel knows how to substitute parameters out of the box, thereby creating an object. For example, when calling the IndexNewPositionCommand command, it will create PositionIndexer(//1) itself.
Tell me, is it possible to somehow transfer an object to class 1, and the second one to be created by itself, otherwise you will have to write too many of these dependencies yourself? Where to dig, where to read?

use App\Services\Search\PositionIndexer;
use Illuminate\Console\Command;
class IndexNewPositionCommand extends Command
{
    //1
    public function __construct(PositionIndexer $indexer) {
        parent::__construct();
    }
    //2
    //public function __construct(Position $position, PositionIndexer $indexer) {
        parent::__construct();
    }
}

use Elasticsearch\Client;
class PositionIndexer
{
    private $client;
    public function __construct(Client $client){
        $this->client = $client;
    }
}

// Хочется передавать $position, а второй параметр, чтобы сам вычислялся и создавался...
$position = Position::findOrFail(1);
$dispatcher->dispatch(new IndexNewPosition($position, new PositionIndexer(new Elasticsearch\Client(итутещёкучавсего))));

Decision
$indexer = resolve('App\Services\Search\PositionIndexer');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2019-08-01
@K0r5hun

https://laravel.com/docs/5.8/container
https://laravel.com/docs/5.8/container#automatic-i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question