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

Поділитися
Вставка
  • Опубліковано 4 жов 2024

КОМЕНТАРІ • 84

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

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

  • @ayazahamed8254
    @ayazahamed8254 Рік тому +1

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

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

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

  • @nabeelyousafpasha
    @nabeelyousafpasha 4 роки тому +7

    Your content is always helpful. Respect from Pakistan.

  • @FranciscoSierraLDU
    @FranciscoSierraLDU 4 роки тому +1

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

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

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

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

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

  • @idanco77
    @idanco77 4 роки тому +1

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

  • @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: ua-cam.com/video/ShrS3HXwzPg/v-deo.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!)

  • @miscellaneousvideos306
    @miscellaneousvideos306 2 роки тому

    Excellent sir.

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

  • @ryiad2010
    @ryiad2010 11 днів тому

    very helpful thanks

  • @fardinmasodi8154
    @fardinmasodi8154 2 роки тому

    your trainings always is the best :)

  • @linasgutauskas5528
    @linasgutauskas5528 4 роки тому +4

    I think fifth way is called "Depency Inversion" ?

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

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

  • @ayenewyihune
    @ayenewyihune Рік тому

    Wow, great video

  • @alila3883
    @alila3883 3 роки тому

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

  • @CoolDispooL
    @CoolDispooL 4 роки тому +2

    Thanks so much for doing that cool content

  • @linkernetir
    @linkernetir Рік тому

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

  • @chico-timido
    @chico-timido 4 роки тому

    Thanks a Lot, very useful content

  • @iedi3
    @iedi3 3 роки тому

    Awesome video, thanks

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

  • @zubayerhossain7074
    @zubayerhossain7074 4 роки тому +1

    5th one is bit tricky, can you make a video on it, 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 ?

  • @ilyasbakirov
    @ilyasbakirov 2 роки тому

    Nice gotchas 👍

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

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

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

  • @mohamedshuaau632
    @mohamedshuaau632 3 роки тому

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

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

  • @targetx1733
    @targetx1733 3 роки тому

    Good work

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

  • @faridnubaili7917
    @faridnubaili7917 Місяць тому

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

  • @dgloria
    @dgloria 4 роки тому

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

  • @kabiraneja7635
    @kabiraneja7635 4 роки тому

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

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

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

  • @АйбатАманбайұлы
    @АйбатАманбайұлы 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?

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

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

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

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

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

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

  • @ramazanaktas748
    @ramazanaktas748 Місяць тому

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

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

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

  • @pedropeter2717
    @pedropeter2717 4 роки тому

    Awesome content. Thanks