Laravel: When to Use Static Methods, Services and Dependency Injection

  Рет қаралды 58,996

Laravel Daily

Laravel Daily

Күн бұрын

A lot is written on the syntax of dependency injections and services. But let's talk about WHY and WHEN to use them, what are the actual benefits and in what cases.
Video is based on a collaborative article from our team: quickadminpanel.com/blog/lara...
A bit more about the structure of Laravel projects - you can find in my online course "How to Structure Laravel Project": laraveldaily.teachable.com/p/...

Пікірлер: 80
@ivanivan9984
@ivanivan9984 Жыл бұрын
No words about how dependency injection helps to testing. And I really think it is the main purpose of this practice.
@KatieGeorgieva
@KatieGeorgieva 3 жыл бұрын
I've read 5 articles on dependency injection and never quite get it. Your approach to show when to use it is very helpful. At last something useful :) Thanks!
@PovilasKorop
@PovilasKorop 3 жыл бұрын
Thanks Antoine, glad to help!
@khatu_shyam
@khatu_shyam 3 жыл бұрын
@@PovilasKorop Thankyou for the wonderful explanation. I was really looking for this kind of video. Before this video, I googled alot but unable to understand the dependency injection but now after this video it's clear. By the way I'm active subscriber of this channel since last 6 months.
@ayazahamed8254
@ayazahamed8254 Жыл бұрын
I listen most of your videos and you have outstanding knowledge in Laravel. Thanks🎉
@michaeldeeming4643
@michaeldeeming4643 3 жыл бұрын
Great video, this is really helpful for myself as I'm a sole self taught developer at a company and have always questioned myself when refactoring code in controllers and how I should refactor the code. Massive help thank you
@idanco77
@idanco77 3 жыл бұрын
Amazing. Thank for your videos. You are making complicated things looks pretty easy
@kaushikkumar2455
@kaushikkumar2455 3 жыл бұрын
Your content are very educational. Now everyday i learn something new about laravel that i found it very hard on documentation just because of your channel... thank u so much
@FranciscoSierraLDU
@FranciscoSierraLDU 3 жыл бұрын
BEST Service providers video ever!!!! Thanks a lot!!!!
@blessingchirume8316
@blessingchirume8316 Жыл бұрын
I think I am now getting addicted to your tutorials thanks for changing coding. Can you also do a tutorial on best practices when working with third party API in a Laravel application.
@nabeelyousafpasha
@nabeelyousafpasha 4 жыл бұрын
Your content is always helpful. Respect from Pakistan.
@hamayoonyousafi555ATgmail
@hamayoonyousafi555ATgmail 2 жыл бұрын
Thank you sir very much for clarifying everything to the simplest possible.
@ebarchiesi
@ebarchiesi Жыл бұрын
This is a great video with all the alternatives to use with Laravel and dependency injection
@sumanthapa7161
@sumanthapa7161 3 жыл бұрын
Your contents are best and very simple to understand , respect from Nepal
@kamyargerami3238
@kamyargerami3238 2 жыл бұрын
thank you, finally i understand what is binding after seeing many videos.
@armanbz7
@armanbz7 2 ай бұрын
Thank you from Iran 🌹
@fardinmasodi8154
@fardinmasodi8154 2 жыл бұрын
your trainings always is the best :)
@pedropeter2717
@pedropeter2717 4 жыл бұрын
Awesome content. Thanks
@alila3883
@alila3883 3 жыл бұрын
Great, It's helpful and your content was a nice chain
@CoolDispooL
@CoolDispooL 4 жыл бұрын
Thanks so much for doing that cool content
@chico-timido
@chico-timido 3 жыл бұрын
Thanks a Lot, very useful content
@iedi3
@iedi3 3 жыл бұрын
Awesome video, thanks
@miscellaneousvideos306
@miscellaneousvideos306 2 жыл бұрын
Excellent sir.
@ayenewyihune
@ayenewyihune Жыл бұрын
Wow, great video
@mohammadashrafuddinferdous8649
@mohammadashrafuddinferdous8649 2 жыл бұрын
Nice explaination. I found di is more effective for almost every cases. So, I try to avoid static method call or fluent interface.
@FranckMercado
@FranckMercado 2 жыл бұрын
Great video, glad you talk about dependency injection. On that matter, I kindly disagree when you say Dependency Injection doesn't bring very much benefit compared to static call. One enormous benefit it offers is using Composition which cleans up your application and puts you in a better place for decoupling from infrastructure services and most importantly, it helps when unit testing your classes as you can mock those dependencies in your tests. You also mention you haven't found Dependency Injection topic on internet very well written for Laravel. Well Dependency Injection is a global principle and used across programming languages, best examples I've seen on internet is with Java, C# and even also with PHP but with more composition oriented and decoupled frameworks like Laminas, Slim, Symfony, etc.
@andibachtiar8788
@andibachtiar8788 2 жыл бұрын
so what is your point about dependency injection topic? you said yourself it more common in java, c# and composition oriented php.
@targetx1733
@targetx1733 3 жыл бұрын
Good work
@zocratiko
@zocratiko 3 жыл бұрын
Thanks, awesome video! the best ever about services. I noticed that in none example use the app() method to call the services... what's the reason why? Thanks a lot!
@vivekwah
@vivekwah 2 жыл бұрын
In one of the interview I have been asked why to use dependencies if we can just instantiate new object in constructor. Also how dependency injection is affected with desctructor.
@emadeldeenali1260
@emadeldeenali1260 2 жыл бұрын
Thank you it is very informative vedio Can we move the code from the service to repository class and centralize the service class ?
@centerdevelopments3533
@centerdevelopments3533 4 жыл бұрын
Awesome! Thank you!). But you talk about very simple logic, the real problems comes when there much more complicated service. For example, what if you have banner rotation, with incoming params, filtering, bot checking, saving banner view and user, tracking info to a database, banner rotation algorithm and other things which should be handled in one request. It is just an example. But maybe you had something like this in your experience and you can show how you organized it. This topic is extremely useful because i searched a lot, but most of examples are so simple.
@PovilasKorop
@PovilasKorop 4 жыл бұрын
Thanks. Well, that is my goal - to explain complex things with simple (but real-life!) example. Because I know my audience, which is mostly junior-mid level developers who want to know the next steps towards complex things, not too deep, I don't want to overwhelm everyone with complex examples. There are people who try to teach mid-senior audience and dive deeper into this, like laravelcoreadventures.com/ or some advanced topics on Laracasts, so probably you need to look somewhere else. But for your example, maybe this video is close to what you mentioned with a lot of actions in one request: kzbin.info/www/bejne/iZnVhGZ-jdythsk
@centerdevelopments3533
@centerdevelopments3533 4 жыл бұрын
@@PovilasKorop Your right, now it is clear for me. Content should cover as much audience as it can. Btw, thanks for your work and feedback. I'll go through your links right now, and keep an eye on your further videos!)
@ilyasbakirov
@ilyasbakirov 2 жыл бұрын
Nice gotchas 👍
@mohamedshuaau632
@mohamedshuaau632 3 жыл бұрын
I knew I have seen you somewhere I have read so many of your articles haha
@linkernetir
@linkernetir Жыл бұрын
very well explained. but it was a little fast :D which was a benefit.
@zubayerhossain7074
@zubayerhossain7074 4 жыл бұрын
5th one is bit tricky, can you make a video on it, Please?
@linasgutauskas5528
@linasgutauskas5528 3 жыл бұрын
I think fifth way is called "Depency Inversion" ?
@yehorpolishchuk8877
@yehorpolishchuk8877 3 жыл бұрын
And what about passing $year parameter? Where shoud it be passed into the constructor when using binding? Is there a way to take parameter value from outside and pass it in "providers"? One more question is why did you miss the providers creation and registration in this video?
@aj98767
@aj98767 3 жыл бұрын
Hey cool article. I will try SOLID-based architecture using your fifth option. But I also just want to ask if your representation of the method within an interface is functional? What I mean, doesn't it needed to be just declared (without brackets) instead of actually specifying the functionality?
@taghwomillionaireo.5543
@taghwomillionaireo.5543 3 жыл бұрын
Yes an interface method should not have a body
@skpao08
@skpao08 2 жыл бұрын
Hello, is it possible to perform dependency injection outside the routes? For example, from a class called Report (which is called via artisan command) I inject a service called ReportService. I have searched for information about it and from what I see it is only possible to use them in routes. Thanks in advance.
@dgloria
@dgloria 3 жыл бұрын
Hi Povilas, how can I tell if my generic code should be in a trait or in a service in Laravel 7 and above? Do they still use traits at all? Thanks.
@PovilasKorop
@PovilasKorop 3 жыл бұрын
I'm planning to shoot a separate video about traits. Next week, probably.
@dgloria
@dgloria 3 жыл бұрын
I've been looking for this since 2 years :D Why this cannot be just copy/pasted into documentation?
@kabiraneja7635
@kabiraneja7635 3 жыл бұрын
Hello sir, I didn't get that reportService interface part can you please help me!!!Just a request sir please
@MegaBlackrocks
@MegaBlackrocks 2 жыл бұрын
If we have a service class with parameter (third way from the article), is it possible to use this class as dependency injection? Thanks in advance.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
At least I haven't done it that way, never seen it.
@midicine2114
@midicine2114 3 жыл бұрын
9:20 So you could bind a mock implementation in dev environment and write unit tests like normal code and It will just used the mocks?
@kaczuszka-dt
@kaczuszka-dt 2 жыл бұрын
yes
@PositiveZahid
@PositiveZahid 2 жыл бұрын
Can you give idea about any open-source Github project that implemented dependency injection and service container? Thanks
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Try to look here: laravelexamples.com/projects
@ajithlal1688
@ajithlal1688 4 жыл бұрын
I don't know this is a stupid question or not but still How to do a Dependency injection for a parameterized service. Like example 3 i think. If a service have a constructor method and initializing one variable when instance is created for the service then, how to do Dependency injection for that class?
@PovilasKorop
@PovilasKorop 4 жыл бұрын
Then you probably want an interface and then binding that service with the parameter you want, in AppServiceProvider. There's no way to instantiate a service with a parameter, without creating its object with that parameter.
@user-jx8uz6tb6k
@user-jx8uz6tb6k 3 жыл бұрын
Does dependency injection return the same instance of the object when injected in different places?
@Lucas-hh4oh
@Lucas-hh4oh 2 жыл бұрын
I've been wondering the same thing. Is it a singleton or not?
@mohammadmohammadi2724
@mohammadmohammadi2724 2 жыл бұрын
It is very good but I have seen some people just move all the code inside of the controller to Service Class. 1 service method per controller method. do you like it?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Also possible, but without looking at the actual code example I can't comment deeper
@divyeshprajapati9376
@divyeshprajapati9376 3 жыл бұрын
I have api and make different service for product,catgeory,customer but i don't know how to passed request params in service becuase I have few parameters like marketCode, lang, device which used in all api & service. Any one can help me on this... Currently I have make BaseService.php file in which I have get requestparams in constructor but problem is in all extended service class I have to call parent::constructor. Any other way some how make it global access for common params..
@KashifAli-gd8pp
@KashifAli-gd8pp 3 жыл бұрын
I want use a variable in all views, Can you guid me how to call it view for every time?
@LaravelDaily
@LaravelDaily 3 жыл бұрын
Use view::share
@dhanushkafernando6316
@dhanushkafernando6316 3 жыл бұрын
Hi,I just saw dependancy injected on below method.Is it secure? or ok to the coding standards? public function CommonFunction() { $code = app('App\Http\Controllers\CommonController'); return $code; }
@muntasirhasan2052
@muntasirhasan2052 3 жыл бұрын
How to create Services? There is no command for it like "php artisan make:service"
@PovilasKorop
@PovilasKorop 3 жыл бұрын
No, there's no such command, Services are created as any other PHP class, manually.
@Denis-di6hc
@Denis-di6hc Жыл бұрын
does using static methods in controllers or repositories to build queries has any security problems ?
@LaravelDaily
@LaravelDaily Жыл бұрын
No
@ricohertha3537
@ricohertha3537 10 ай бұрын
Don't use static methods in services (controllers and repositories are services too). There it no serious reason to use static methods in services. static methods are not scoped - no dependency injection possible - can't use with interfaces The advantages dependency injection are: - decoupling the creation of object (in other word, separate usage from the creation of object) - ability to replace dependencies (eg: repository, logger ...) without changing the class that uses it(Controller) promotes "Code to interface not to implementation" principle - ability to create and use mock dependency during test (if we want to use a Mock of PersonRepository during test instead of a real instance.. we can create Mock PersonRepository object and let DI framework inject to PersonService)
@statem9357
@statem9357 4 жыл бұрын
How about Trait ? i mean instead of using Service, how about using Trait ?
@PovilasKorop
@PovilasKorop 4 жыл бұрын
Yes, there are times when there's no need for proper OOP solution and Trait is enough. It's pretty rare. I'm planning to shoot a separate video about Traits vs Services.
@TheSathivel
@TheSathivel 3 жыл бұрын
Could you please explain how can I achieve for the following in laravel 8 . 1). Dependency Injection - Use dependency injection for locating controllers for Development and production environment. 2). Dependency Injection - for setting parameters for the Dev and Production environment. Thank you.
@PovilasKorop
@PovilasKorop 3 жыл бұрын
Why do you need a dependency injection for this? Parameters should come from config('xxxxx') that should come from env() and in your dev/prod environments you should have different .env file values.
@TheSathivel
@TheSathivel 3 жыл бұрын
@@PovilasKorop actually this is the interview question. I need to do some GET and POST api and also asked me to do Dependency injection to locate controller for dev and production environment.
@PovilasKorop
@PovilasKorop 3 жыл бұрын
@@TheSathivel Very weird question, I don't see any practical value of doing that.
@sadekhossain9566
@sadekhossain9566 3 жыл бұрын
if we use interface then we lose the benefit of using the service class everywhere. lets say service class has 5 methods and in one controller need 3 methods to reuse the service. in this case we wont be able to do it with interface because this class expect to use all the methods implementation!
@IWasHereFirst2
@IWasHereFirst2 3 жыл бұрын
A class can implement multiple interfaces. Just split your interface
@Ballltas
@Ballltas 5 ай бұрын
I dont agree with DI part how and when to use it. Using DI is always beneficial over other methods. It improve scalability. Imagine if you want to inject additional services so now you have to know where are all those objects created with new Services(With $parameters) and then you need to add a new parameter everywhere you instantiate it. Also think about unit tests. You can not mock objects that are created as new Something() inside a function that you are testing. So in conclusion using new operator to create service/repo objects is antipatern.
@natenatebobate
@natenatebobate 3 жыл бұрын
Sorry to be such a downer, but this didn’t work for me. I really like your stuff and I have you bookmarked as a separate folder and planning to get your courses soon. But for me this lesson didn't have the intended effect. I had such high hopes that finally someone had a good explanation of some of these concepts. Like other commenters have said, I've been desperate for someone to properly explain DI vs what else(?); there's gotta be 100 "simple" videos out there on DI alone. I think your example was way too fast and complex. Why not use a simple Post model with a live-coded web page like you usually do, instead of working from a written explanation and hand gestures? Without displaying how the different coding methods affect a webpage (as you usually do), and comparing those effects, for me it was entirely lost.
Two Things Laravel Services Should NOT Do
8:20
Laravel Daily
Рет қаралды 21 М.
Cache Eloquent Query Results to Load Pages Instantly
5:43
Laravel Daily
Рет қаралды 59 М.
FOOTBALL WITH PLAY BUTTONS ▶️❤️ #roadto100million
00:20
Celine Dept
Рет қаралды 35 МЛН
Универ. 10 лет спустя - ВСЕ СЕРИИ ПОДРЯД
9:04:59
Комедии 2023
Рет қаралды 2,6 МЛН
Static Methods in Laravel/PHP: When and How?
10:39
Laravel Daily
Рет қаралды 16 М.
SOLID Principles in Laravel: 5 Examples (+ New Course!)
21:07
Laravel Daily
Рет қаралды 71 М.
Optimizing Eloquent: Running Out Of Memory?
6:11
Laravel Daily
Рет қаралды 42 М.
What is Dependency Injection PHP - in 5 Minutes
5:06
Daily Tuition
Рет қаралды 17 М.
Laravel Method Injection: Boost Your Code Quality #laravel #shorts
0:56
9 Tips for Shorter Laravel Code
10:16
Laravel Daily
Рет қаралды 60 М.
Eating ice-cream in secret from child #shorts
0:19
Secret Vlog
Рет қаралды 6 МЛН
Qual Fita NÃO vai Me AGUENTAR😱 #shorts
0:45
Lucan Pevidor
Рет қаралды 13 МЛН
MEHDI AMRI - ILS M’ONT CHOQUÉ…صدمني 🤯🤯🇲🇦
0:15
У нас ОТКЛЮЧИЛИ ВОДУ!
0:45
Привет, Я Ника!
Рет қаралды 1,6 МЛН