Laravel + Service Pattern + DTOs = ❤️❤️❤️

Поділитися
Вставка
  • Опубліковано 9 січ 2023
  • Hi guys!
    In this video series, I'll be showcasing a simple way to integrate service pattern into existing Laravel applications. We'll start with a super simple example - an app that stores blog posts from the app and the api.
    We'll do a couple of iterations before landing in type-safe service pattern solution that utilizes DTOs.
    For more content visit saaslaravel.com
  • Наука та технологія

КОМЕНТАРІ • 100

  • @free2idol1
    @free2idol1 10 місяців тому +15

    11:15 using `tap()` to get the updated model instance after the update.
    This is a great thing for me.
    Thanks for fabulous video.

  • @kpomeru
    @kpomeru 11 місяців тому +1

    I had to take my time to understand this from the solution back to how it was implemented. This is insightful

  • @peterpardo4138
    @peterpardo4138 9 місяців тому +1

    This is a GEM! Thank you so much for sharing this. I really appreciate you!

  • @GayanSanjeewaKarunarathne
    @GayanSanjeewaKarunarathne 8 місяців тому +1

    This is just awesome. Good job mate! To be honest I think you covered more than just Services and DTOs. Keep it up 👍

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

    Very very useful! Will definitely use it in my next project! Looks very promising.

  • @e-raticartist
    @e-raticartist 2 місяці тому

    huge improvement in the quality of my code after this, next level content

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

    This video was really helpful, a lot of things now make sense. Thanks so much.

  • @SerG63rus
    @SerG63rus Рік тому +7

    One of the best videos which let’s you understand clever way to write code in just less than 20min.
    Very very useful and pure.
    Thank you!

    • @VimKanzo
      @VimKanzo 9 місяців тому

      I couldn't agree any better

  • @soyarenamovediza6498
    @soyarenamovediza6498 5 місяців тому

    Loved this video, thanks! You explained many patterns and did very well. I would like a video from yourself explaining some real life scenarios where these patterns really shine by themselves. I’ll share this video.

  • @unknownstalker2624
    @unknownstalker2624 3 місяці тому

    Man, you are just awesome! Your content really helped me!

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

    I like this video. This is exactly the pattern I want. Thanks!

  • @XTishka1980
    @XTishka1980 2 місяці тому

    Amazing! Thank you for your lessons

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

    Very nice, simple and clean description about Services and DTOs in Laravel, thanks man 👍

  • @natenatters
    @natenatters Рік тому +10

    Great video! Thats very similar to how we are structuring our application. I like your approach of showing the iterations, a good way to learn. Thanks.

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

      Thanks Natan! If you sprinkle some DDD on top it gets even better 🤓

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

    You just earned one more subscriber, thanks for sharing valuable information...😊

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

    Great stuff man! thanks for sharing

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

    Muy buen video. Muy entendible y progresivo.

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

    Very cool! Thanks for the video
    Keep making more videos please!

  • @mohammadravand4351
    @mohammadravand4351 7 місяців тому

    thank you very mutch, this is very excelent video a bout laravel service pattern, 😍😍😍🥰

  • @chlouis-girardot
    @chlouis-girardot Рік тому

    Nice work ! Thanks for sharing 🙏

  • @AhmadAli-jb6ri
    @AhmadAli-jb6ri 4 місяці тому

    ❤❤ Thanks for this tutorial...

  • @SeyedaMansour
    @SeyedaMansour 9 місяців тому +1

    wow, this was great

  • @AdrianoAlves7
    @AdrianoAlves7 Рік тому +20

    I really do not understand why add complexity and more entities when we have some methods in Laravel to get all the validated data from a request. I like and i employ the Service Pattern because we can separate the app business logic from models and controllers, but the DTO.. oh my... i can't see any need for this. I would like to see a Video from you about Model Events and BroadCasting them. Thank you and congratulations for your great work, Przemyslaw. Greetings from Brazil.

    • @saaslaravel
      @saaslaravel  Рік тому +25

      Hi Adriano! Thanks for the kind words. Lemme explain the reasoning:
      The biggest reason why DTOs are useful is it unifies the data passage through your application.
      Let's say you have a piece of business logic that needs to be executed from your app, public api, command and a job. DTOs ensure that proper data gets passed to the service. Also, if you ever add a property, it will cause errors in places where it was not implemented / handled which also prevents bugs

    • @felipeflashmaster
      @felipeflashmaster 8 місяців тому +1

      So using the Model itself as a DTO would be the same, right? or how in typescript to use an interface

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

      @@felipeflashmaster using the Model as a DTO itself would clutter the Model into a mess, if you're planning to implement DRY, that would not be a recommended approach.

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

    Helpful content! Thank u!

  • @programmertelo
    @programmertelo 9 днів тому

    thanks for the great video

  • @MrSfinks13
    @MrSfinks13 9 місяців тому

    Cool! Thank you!

  • @midclock
    @midclock 2 місяці тому

    Nice tutorial!
    You can check ide-helper to generate model auto completion for properties.
    For dtos I find laravel-data by spatie a very good solution.
    Cheers

    • @saaslaravel
      @saaslaravel  2 місяці тому

      Yeah I use both of them in my workflow! Def worth checking out for anybody interested though!

  • @laxman123in
    @laxman123in 9 місяців тому

    Awesome

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

    This is good. Simple and easy to understand...
    I have always wanted somethinh simple for dto instead of a package...
    Will be improving some project with this implementation

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

      Thanks! Glad you enjoyed it and good luck on your project

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

      While refatoring, I wonder how you would handle Request for update that has fields set as sometimes for validation. Considering for patch request, not all fields will be supplied.

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

      @@codewithtee Often times I just duplicate the request, I like this approach because it's the most flexible one. You could try and extract common rules but as the resource gets more complex I think it just adds unnecessary complexity in something that should be sime. Another solution is to simply check the method in the request and modify the rules array but I find it harder to read :)

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

      same here too..

  • @B0re_d
    @B0re_d 20 днів тому

    I would add the transformation method to request classes. In my opinion you should not have to extend DTO classes when adding new pieces of code eg. API v2 instead you should have a method called asDto(or toDto) in the request class and call them instead of making X static factory methods. Overall great content :)

  • @muhammadumarsotvoldiev8768
    @muhammadumarsotvoldiev8768 6 годин тому

    Thank you very much!

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

    awesome video dude! saw it again :D

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

    B-e-a-u-tiful!

  • @user-dk4or7bs2q
    @user-dk4or7bs2q Рік тому

    So nice

  • @NoNameUkr
    @NoNameUkr 7 місяців тому +1

    I prefer to pass array into static DTO method, then Request, for me its much safety, u can use this DTO from wherever u want, not only from Controller. Example: tomorow u will need to create Post from console command or from Job

    • @saaslaravel
      @saaslaravel  6 місяців тому

      Which you can still do by instantiating the DTO from the constructor. Imo array passing loses all of the benefits of type checking built into the class

  • @borakayalar
    @borakayalar 6 місяців тому

    Perfect

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

    Cool

  • @nikolayrogoza4240
    @nikolayrogoza4240 26 днів тому

    Great tips, but i more like to use different actions as class, not as a part of service. Its easy to extend from basic model to others

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

    this is a very cool video.. nicely explained. what about making a video about php types?

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

      Thanks so much! Types as in strings, ints etc? What would you like to know about them?

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

      @@saaslaravel everything hehe, like using a separated file, best practices, how to use it in a function like boot(): void and all that stuff.

  • @antonsobchuk7690
    @antonsobchuk7690 10 місяців тому

    Great job, man. What’s the theme of phpstorm you are using btw?

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

    Really good man!
    I would like to know what you think about adding an extra layer: the repository.
    Because thats kinda whats going on my in job rn, laravel + service pattern + dto + repository,
    I feel like the Model itself could act as the Repository, what do you think?

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

      It really depends on what you are looking for from the solution. I'd say - if you don't have a good reason to introduce a repository - don't do it. If you want to have more fine grained control over your persistence layer (i.e to handle CQRS more easily) go for repository!

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

    very informative, thank you very much!
    what theme do you use in your IDE?

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

      Thank you! It's called Catpuccino Mocha

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

    This is a really great video! Is there a repository where I can check the code for this example? I would greatly appreciate it.

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

      I don't have it unfortunately but will probably start doing it going forward

  • @VipStudio
    @VipStudio 3 місяці тому

    When you have form request class included into ur method you dont need to do $request->validated cuz the data is already validated otherwise it throws validate exception until first line of code starts compile from function

    • @VipStudio
      @VipStudio 3 місяці тому

      And you dont need to use Dto u can just do create($request) //already validated clean data

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

    Thanks is very helpful! I want ask as how use DTO when you have relations for example Post has many Comments. In PostDTO comments will be array/collections of CommentsDTO or simple array of ids?

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

      Thanks Artem! It really depends on the scenario, I think there is a use-case for both
      Option A: Nested models created all at once.
      Example: You create BlogPost and it has different "sections" of content, or you create a Recipe that has Ingredients
      Solution: In this example you'd have a RecipeDTO that has all of the recipe properties, and either an array of IngrednetDTO, or a IngredientDtoCollection (the latter if you want something that's more type-safe)
      Option B: Creating a new model and associating it with existing ones
      Example: You select which users should have access to a project
      Solution: In this example you'd have a ProjectDTO, that'd contain an array with IDs of users to associate and then simply attach it to a pivot table
      Lemme know if this makes sense!

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

      @@saaslaravel Thank you for your help.

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

    You don’t need constructor, you can bind service in controller method automatically...

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

      That's true, but I prefer using constructor. The method tends to have 2/3/4 arguments - with type hints it takes a lot of space, and when it lives on constructor level I can just define it once :D

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

      @@saaslaravel makes sense as well :) I tend to use actions in method binding and if I use a service in more than one method I would promote it to the constructor.

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

    Hey! How do you approach having different validation rules in the store and update actions? For example, a StoreBlogRequest which marks all fields as required, VS an UpdateBlogRequest which doesn't (for example, you just wanna update the name). Would you create more than one DTO and mark the properties as nullable?

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

      Hey there! It depends on the situation, generally speaking with updates I'd not go with nulls because partial updates are pretty sexy - if you use spatie/laravel-data - they handle it out of the box with Optional type hint

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

    Well done bro! Great videos. But I have a question here, so what is the benefit of using DTOs? I'm interested to use this in my project, is it hard to implemented in existing project. I'm also using service class.

    • @saaslaravel
      @saaslaravel  Рік тому +2

      The main benefit is making sure that the data you're passing is valid data that service can consume. This is especially useful when you have multiple pieces of app - console, public api and internal api calling the same service. You can just start implementing it on new services and then gradually go over existing code! Hope that helps :)

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

      @@saaslaravel Obrigado !

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

      Además que simplifica el constructor

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

    5:50 - what about duplication in BlogPostRequest validation for api and app? Can we get rid of it?

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

    Very nice tutorial. But i have a question, how to use DTO in many relational data like transaction with many items or something?. and we'll be use service as well,

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

      It really depends on the usecase so it's hard to give you a good response here but you can also nest them and utilize arrays with phpdoc type hinting to skip some of the type limitations of php

  • @JSONFX
    @JSONFX 3 місяці тому

    What font are you using on this video? Thanks!

  • @Pavelbrov
    @Pavelbrov 9 місяців тому +1

    Is "laravel-data" package from spatie doing something similar?

    • @saaslaravel
      @saaslaravel  9 місяців тому +1

      Yes, it's just a concept that you need to know from scratch. Just a regular, plan, old PHP class. Nothing wrong with using the package!

  • @iqbalrafli2191
    @iqbalrafli2191 8 місяців тому

    Good video, but i have a questions. What if we want to store data to two or more table from one endpoint controller?

    • @saaslaravel
      @saaslaravel  8 місяців тому

      You can include all data into one dto or pass two separate DTOs. It will depend on the usecase

  • @mihaes7172
    @mihaes7172 5 місяців тому

    I don't understand why instantiating a readonly DTO just to pass request vars to a writing service method? what's the 'secret' between request vars and service update method that dto needs to exists inside same controller method, concerning the same Post model? what if there are 25->50 controllers & models in the application? that would generate a lot of fancy classes, code to be reviewed, etc.
    Sometimes we go overboard for the sake of buzzwords....

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

    17:20 - Shouldn't our DTO have a method like toArray so that we can manually avoid passing all the parameters? I mean, they correspond to the properties of the model. Or is this a bad practice?
    Like this
    public function toArray(): array
    {
    $properties = get_object_vars($this);
    $array = [];
    foreach ($properties as $key => $value) {
    $snakeCaseKey = Str::snake($key);
    $array[$snakeCaseKey] = $value;
    }
    return $array;
    }
    and then BlogPost::create($dto->toArray());

    • @saaslaravel
      @saaslaravel  Місяць тому +1

      I prefer to be explicit when possible, realistically, just use spatie/laravel-data which handles this out of the box

  • @3dxspx703
    @3dxspx703 Місяць тому +1

    Yikes. Model mutators and observers will be enough guys. But if you want to Over-engineer your code, then go on with dto or something like repository pattern. 😅

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

      Until your app had 1200 endpoints and some places haven't been touched for years - yeah

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

      @@saaslaravel yeah? But I prefer laravel's defaults for easier maintenance and debugging. Also KISS. Pfft

  • @LucasOliveira-ny6kw
    @LucasOliveira-ny6kw 2 місяці тому

    .

  • @deecee2204
    @deecee2204 6 місяців тому +1

    Why is this so painful to watch? no offense

    • @saaslaravel
      @saaslaravel  6 місяців тому +1

      Idk, why is it bud?

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

      million times better and understandable than any indian out there that i cannot understand

  • @MrSfinks13
    @MrSfinks13 5 місяців тому

    Thank you! Very useful video, realy!