Service container in Laravel - architectural concept and injection in Laravel

  Рет қаралды 10,560

Просто о Laravel. CutCode

Просто о Laravel. CutCode

Күн бұрын

In today's lesson, we will touch on an important and interesting topic - service container (laravel service container). This is an architectural concept in Laravel that is important to know and understand, but for many newbies it can be a dark forest.
serviceconteiner # laravel # cutcode
❗️❗️❗️How to make complex sites in laravel? It's easy with cutcode!
Support my project - cutcode.ru/
Buy me coffee - buymeacoffee.com/cutcode
🤖🤖🤖My assistant Taylor is ready to give you a present. Pick up here - cutcode.ru/chat-bot
-------------------------------------------------- -------------------------------
⏰ Timecodes:
00:00 Introduction
00:27 Laravel Documentation Overview
02:00 A little story about how I studied service container many years ago
02:58 Class injection example
04:48 What Happens When Specifying an Argument Type
06:01 An example with interface injection
Friends, I welcome everyone to the Cutcode channel! In today's lesson, we will touch on an important and interesting topic - service container (laravel service container). This is an architectural concept in Laravel that is important to know and understand, but for many newbies it can be a dark forest.
The Laravel documentation describes it in detail, but there is a lot of complicated, incomprehensible text. Therefore, we will now try to illuminate it with an example in simple words, so that everything becomes immediately clear and in the future, when you hear such a phrase as a service container, you immediately understand what it is about and how it all works, all this magic.
In the documentation, we immediately see a simple example, we see the service container controller working for us as described in the documentation in controllers, in event listeners, middleware and elsewhere. But I'll tell you right away in 90 percent of cases, or even more, this is only used in controllers. Therefore, in today's lesson we will just consider controllers.
We return to the documentation where a simple example is shown to us. The example controller user has a construct method. It can also be any other method in this controller. Well, in any other Laravel controllers.
We then pass the argument to the users function specifying the type of the users class of the repository. At the same time, it is in Laravel that this service container magic happens and we create an instance of the user class of the repository with which we can already work inside this method. We can also pass any of our classes and can pass and inject multiple classes, specifying them separated by commas. Moving a little from the documentation, I will say that when I just started learning Laravel and it was version 6 or even 5, and by default, when generating a controller via the command line, there was a default index method and it had just an injection of the request facade. And I thought that by default only the request facade, or request forms, or some parameters from the route are available to us, and only later I delved into the Laravel concept and realized how interesting it all works.
In addition to class injection, we can also inject interfaces and later bind them to some class that inherits this interface. But we will talk about this now in more detail in the examples, so that it becomes clearer when and why such an approach should be applied.
Let's open up the code and walk through live examples.
-------------------------------------------------- -------------------------------
📹 share this video with your friends:
• Service container в La...
🔔 subscribe to the KZbin channel: / @cutcoderu
📼 Laravel course from scratch:
• Курс по Laravel 8 обуч...
Service conteiner in Laravel - architectural concept and injection in Laravel
-------------------------------------------------- -------------------------------
🔗 our website: cutcode.ru/
📷 our instagram: / cutcoderu

Пікірлер: 30
@alexmercer531
@alexmercer531 2 жыл бұрын
Пожалуй, самое лучшее и короткое объяснение этой темы. Спасибо.
@user-ck6sx5tr8g
@user-ck6sx5tr8g 9 ай бұрын
Отличное объяснение спасибо! Начинает потихоньку доходить)
@CutCodeRu
@CutCodeRu 8 ай бұрын
🤗
@aleksandrkomarov3201
@aleksandrkomarov3201 Жыл бұрын
Полезно. Кратко. Спасибо
@modestusmunh93
@modestusmunh93 Жыл бұрын
Спасибо!
@user-rz4uf7yp7b
@user-rz4uf7yp7b 2 жыл бұрын
Как во время) спасибо !
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Спасибо за просмотр!)
@user-nf1td4hh7y
@user-nf1td4hh7y 2 ай бұрын
Супер спасибо
@CutCodeRu
@CutCodeRu Ай бұрын
💪
@user-qw5sd7hf2e
@user-qw5sd7hf2e 2 жыл бұрын
Спасибо
@CutCodeRu
@CutCodeRu 2 жыл бұрын
🤖
@plutuss
@plutuss 2 жыл бұрын
Спасибо очень полезная тема. Если можно подробней про сервисный слой, и вынос логики с контролера в сервисы. Интересны примеры на практике. Сейчас разбираюсь с этим. Часто спрашивают на собеседование...
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Рад стараться! Спасибо за просмотр! Посмотрите вот этот ролик kzbin.info/www/bejne/aaDTYapjataCiMU возможно он ответит на ваши вопросы, он скажем так является второй частью этого ролика
@plutuss
@plutuss 2 жыл бұрын
@@CutCodeRu Спасибо сейчас посмотрю
@abdullaalt6183
@abdullaalt6183 Жыл бұрын
а как передать свой параметр в сервис, типа return new TestService($id); какое-нибудь динамическое значение
@vladzaiko5012
@vladzaiko5012 6 ай бұрын
А как лучше сделать, если надо вместо интерфейса подставлять обьект или SlackNotificator или TelegramNotificator в зависимости от параметра в реквесте ?
@user-ib9py6bv4t
@user-ib9py6bv4t 2 жыл бұрын
Здорово! Сделайте пожалуйста видео о том, как работать с датой и временем по Гривичу, чтобы они отображались в соответствии таймзоной
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Добрый день! Не совсем понял! Можно подробнее контекст вашей задачи! Если вы просто хотите сменить таймзону то зайдите в config/app.php и установите 'timezone' => 'GMT' или о чем речь?
@alexandershestakov2914
@alexandershestakov2914 2 жыл бұрын
А был ли у вас ролик по Laradock?
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Пока такого не было
@vitalyzibulski495
@vitalyzibulski495 2 жыл бұрын
а если к интерфейсу привязаны два класса, в одном случае нужно инджектить первый класс, а во втором методе второй класс, как нужно биндить?
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Хороший вопрос, которые я замечательно упустил при создании ролика! Вам необходимо использовать условия, вот вам ссылка на документацию прямо в необходимый раздел laravel.com/docs/8.x/container#contextual-binding
@user-hs9jm2ph1w
@user-hs9jm2ph1w 2 жыл бұрын
@@CutCodeRu все рано запутано не много и не понятно
@Mr.Capone-
@Mr.Capone- 2 жыл бұрын
ооО. прям в самое время когда мне сегодня надо было жене подарить вчерашний новый год....))
@CutCodeRu
@CutCodeRu 2 жыл бұрын
Ниче не понял))
@wtfisgoingon101
@wtfisgoingon101 Жыл бұрын
вместо того чтобы пять раз твердить про магию сервис контейнера можно один раз показать пальцем на сущность, которая является этим самым сервис контейнером
@inilim
@inilim 4 ай бұрын
Очень важный вопрос, сервис провайдеры регистрируются и выполняются все без исключения, даже те которые не нужны? Например, у нас 100 контроллеров, под каждый контроллер свой сервис провайдер, заходя на один контроллера, запускаются все 100...
@CutCodeRu
@CutCodeRu 4 ай бұрын
Сервич провайдеры отношения к контроллерам не имеют загружаться будут все да
@AKAAAAAAAAAAAAAA
@AKAAAAAAAAAAAAAA 3 ай бұрын
Скорее всего спросить хотели о сервис-контейнере, но суть ответа от этого, очевидно, не меняется.
Создание собственных глобальных helpers в Laravel
4:38
Просто о Laravel. CutCode
Рет қаралды 2,9 М.
Pipelines в Laravel. Для тех кто не знал.
10:06
Просто о Laravel. CutCode
Рет қаралды 11 М.
Wait for the last one! 👀
00:28
Josh Horton
Рет қаралды 110 МЛН
Climbing to 18M Subscribers 🎉
00:32
Matt Larose
Рет қаралды 36 МЛН
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 12 МЛН
Пробую самое сладкое вещество во Вселенной
00:41
Laravel Controllers: Concept of Service and Actions
6:15
Просто о Laravel. CutCode
Рет қаралды 10 М.
Laravel 10. Service Container, Service Providers и Facades в Laravel
24:52
Андрей Кудлай
Рет қаралды 3,6 М.
Фасады (facade) в Laravel. Что это и для чего используются
10:22
PHP-DI - сервис контейнер
48:05
WebForMySelf
Рет қаралды 11 М.
Laravel. Сервисы, контракты и внедрение зависимостей
29:18
Lectoria. Обучение веб-разработке.
Рет қаралды 21 М.
PHPDoc и Laravel IDE helper. Для тех, кто не знал
11:43
Просто о Laravel. CutCode
Рет қаралды 8 М.
Как использовать очереди (Queues/Jobs) в Laravel
13:46
Просто о Laravel. CutCode
Рет қаралды 21 М.
Wait for the last one! 👀
00:28
Josh Horton
Рет қаралды 110 МЛН