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

Поделиться
HTML-код
  • Опубликовано: 30 сен 2024

Комментарии • 84

  • @KatieGeorgieva
    @KatieGeorgieva 4 года назад +43

    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 4 года назад +1

      Thanks Antoine, glad to help!

    • @khatu_shyam
      @khatu_shyam 4 года назад

      @@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.

  • @ivanivan9984
    @ivanivan9984 Год назад +5

    No words about how dependency injection helps to testing. And I really think it is the main purpose of this practice.

    • @InfiniteTwice
      @InfiniteTwice Месяц назад +1

      I was about to write the same comment.
      It's a very important reason.

  • @PositiveZahid
    @PositiveZahid 2 года назад +1

    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

  • @nabeelyousafpasha
    @nabeelyousafpasha 4 года назад +7

    Your content is always helpful. Respect from Pakistan.

  • @linasgutauskas5528
    @linasgutauskas5528 4 года назад +4

    I think fifth way is called "Depency Inversion" ?

  • @faridnubaili7917
    @faridnubaili7917 Месяц назад

    I think the service dependency injection is enough. Still dont have any idea of the 5th way benefit.

  • @ramazanaktas748
    @ramazanaktas748 Месяц назад

    Aren't you all tech guys? Why is this video 360p?

  • @Ballltas
    @Ballltas 8 месяцев назад

    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.

  • @kaushikkumar2455
    @kaushikkumar2455 3 года назад +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

  • @ayazahamed8254
    @ayazahamed8254 Год назад +1

    I listen most of your videos and you have outstanding knowledge in Laravel. Thanks🎉

  • @linkernetir
    @linkernetir Год назад

    very well explained. but it was a little fast :D which was a benefit.

  • @ryiad2010
    @ryiad2010 6 дней назад

    very helpful thanks

  • @yehorpolishchuk8877
    @yehorpolishchuk8877 3 года назад +1

    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?

  • @blessingchirume8316
    @blessingchirume8316 2 года назад +1

    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.

  • @ajithlal1688
    @ajithlal1688 4 года назад +1

    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.

  • @FranciscoSierraLDU
    @FranciscoSierraLDU 4 года назад +1

    BEST Service providers video ever!!!!
    Thanks a lot!!!!

  • @zubayerhossain7074
    @zubayerhossain7074 4 года назад +1

    5th one is bit tricky, can you make a video on it, Please?

  • @FranckMercado
    @FranckMercado 2 года назад +1

    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.

  • @armanbz7
    @armanbz7 5 месяцев назад

    Thank you from Iran 🌹

  • @aj98767
    @aj98767 3 года назад +1

    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?

  • @dgloria
    @dgloria 4 года назад +1

    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 4 года назад +3

      I'm planning to shoot a separate video about traits. Next week, probably.

  • @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 года назад +1

      Also possible, but without looking at the actual code example I can't comment deeper

  • @CoolDispooL
    @CoolDispooL 4 года назад +2

    Thanks so much for doing that cool content

  • @idanco77
    @idanco77 4 года назад +1

    Amazing. Thank for your videos. You are making complicated things looks pretty easy

  • @ayenewyihune
    @ayenewyihune Год назад

    Wow, great video

  • @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..

  • @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;
    }

  • @ilyasbakirov
    @ilyasbakirov 2 года назад

    Nice gotchas 👍

  • @miscellaneousvideos306
    @miscellaneousvideos306 2 года назад

    Excellent sir.

  • @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.

  • @michaeldeeming4643
    @michaeldeeming4643 3 года назад +1

    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

  • @kamyargerami3238
    @kamyargerami3238 2 года назад

    thank you, finally i understand what is binding after seeing many videos.

  • @kabiraneja7635
    @kabiraneja7635 4 года назад

    Hello sir, I didn't get that reportService interface part can you please help me!!!Just a request sir please

  • @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 ?

  • @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.

  • @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!

  • @ebarchiesi
    @ebarchiesi 2 года назад

    This is a great video with all the alternatives to use with Laravel and dependency injection

  • @user-gf3hf5ri8b
    @user-gf3hf5ri8b 2 года назад

    Thank you sir very much for clarifying everything to the simplest possible.

  • @sumanthapa7161
    @sumanthapa7161 3 года назад

    Your contents are best and very simple to understand , respect from Nepal

  • @centerdevelopments3533
    @centerdevelopments3533 4 года назад +1

    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 года назад +2

      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: ruclips.net/video/ShrS3HXwzPg/видео.html

    • @centerdevelopments3533
      @centerdevelopments3533 4 года назад +1

      @@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!)

  • @dgloria
    @dgloria 4 года назад

    I've been looking for this since 2 years :D Why this cannot be just copy/pasted into documentation?

  • @Denis-di6hc
    @Denis-di6hc Год назад

    does using static methods in controllers or repositories to build queries has any security problems ?

    • @LaravelDaily
      @LaravelDaily  Год назад +1

      No

    • @ricohertha3537
      @ricohertha3537 Год назад

      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)

  • @vivekwah
    @vivekwah 3 года назад

    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.

  • @alila3883
    @alila3883 3 года назад

    Great, It's helpful and your content was a nice chain

  • @mohamedshuaau632
    @mohamedshuaau632 3 года назад

    I knew I have seen you somewhere
    I have read so many of your articles haha

  • @fardinmasodi8154
    @fardinmasodi8154 2 года назад

    your trainings always is the best :)

  • @chico-timido
    @chico-timido 4 года назад

    Thanks a Lot, very useful content

  • @iedi3
    @iedi3 3 года назад

    Awesome video, thanks

  • @MegaBlackrocks
    @MegaBlackrocks 3 года назад

    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  3 года назад

      At least I haven't done it that way, never seen it.

  • @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.

  • @statem9357
    @statem9357 4 года назад

    How about Trait ? i mean instead of using Service, how about using Trait ?

    • @PovilasKorop
      @PovilasKorop 4 года назад +1

      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.

  • @АйбатАманбайұлы
    @АйбатАманбайұлы 3 года назад

    Does dependency injection return the same instance of the object when injected in different places?

    • @Lucas-hh4oh
      @Lucas-hh4oh 3 года назад

      I've been wondering the same thing. Is it a singleton or not?

  • @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?

  • @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?

  • @sadekhossain9566
    @sadekhossain9566 4 года назад

    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 4 года назад +2

      A class can implement multiple interfaces. Just split your interface

  • @targetx1733
    @targetx1733 3 года назад

    Good work

  • @pedropeter2717
    @pedropeter2717 4 года назад

    Awesome content. Thanks

  • @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.

  • @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.