Composition vs Inheritance in PHP With Practical Examples - Full PHP 8 Tutorial

Поделиться
HTML-код
  • Опубликовано: 13 сен 2024
  • In this lesson, we talk about composition & inheritance. Why inheritance can be a bad idea & how composition can be used instead with practical examples.
    SOME OF THE WAYS YOU CAN SUPPORT THE CHANNEL
    👍 Smash the like button
    🤝 Subscribe to the channel & turn the notifications on
    💬 Post comments, any feedback is greatly appreciated
    ⭐ Become a Patreon: / programwithgio
    THANK YOU!
    🛠️ TOOLS & SERVICES I USE
    Digital Ocean Hosting - Get 100$ credit - m.do.co/c/38b9...
    Domains on Namecheap - namecheap.pxf....
    Envato Elements - 1.envato.marke...
    Adobe Photoshop & Premiere - clk.tradedoubl...
    COURSE PLAYLIST
    • Learn PHP The Right Wa...
    RESOURCES
    Inheritance lesson 2.9 - • PHP - Inheritance Expl...
    Interfaces lesson 2.11 - • PHP Interfaces & Polym...
    ** Affiliate Disclaimer: Some of the above links may be affiliate links, which may generate me a sales commission at no additional cost to you.

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

  • @mwaas
    @mwaas Год назад +14

    All the courses that I watched about php explain php itself , but gio teaches you how to be good programer using php.
    A big thank you to you

  • @benderbg
    @benderbg 8 дней назад

    I really liked this lesson with slides and just explaining the code. Seems like it saves you time from typing so you can cover a lot more information. Using gaming terminology to explain concepts is a great idea.

  • @Necropheliac
    @Necropheliac Год назад +3

    On the last example where you were talking about composition being more useful than inheritance with things like pets or monsters both needing an attack method, I agree with that line of thinking but I think in that particular situation it would be better to use Traits rather than injecting more parameters into the constructors. The reason why is because this has the potential to sprawl out into a very intense amount of composition over time, and it becomes rather complicated to manage class instantiations that require a growing number of compositional inclusions. Traits allow you to embed that compositional functionality directly into the right class without retroactively editing the object instantiations at all the places you have used that class call in the code.

    • @ProgramWithGio
      @ProgramWithGio  Год назад +2

      Yes & no. Traits sort of give illusion of composition while not exactly being composition. When it comes to testability, the real composition through construction injection is the right way. That being said, using traits is also a good way to achieve somewhat the same end-goal.

    • @vegekou100
      @vegekou100 10 месяцев назад

      @@ProgramWithGio I thought you would ended up with Interfaces, what do you think about it? Could it work?
      Though if I try to figured it out, it would look a lot like using traits.

    • @ProgramWithGio
      @ProgramWithGio  10 месяцев назад +1

      @@vegekou100 interfaces & dependency injection is the right way

  • @ZeDlinG67
    @ZeDlinG67 10 месяцев назад +1

    Very nice video! I'm glad that some people take PHP seriously - most of them (I think) just remember the PHP3-4 days, where it was kinda like Javascript.
    One big note for everybody who is watching this, If you are working in finance territory (like invoices in the example),
    NEVER use the basic math operations, use the bc_math extension, or use "Money for PHP" for currencies!
    The reason is that default float point operations are not precise enough, and especially if you are exchanging, you'll get 1-2 cent differences because of rounding errors

    • @ProgramWithGio
      @ProgramWithGio  10 месяцев назад

      Yup thats the way but for smaller projects where fractions don't matter much floats are fine. As long as you don't compare them directly for equality.

  • @uxweb
    @uxweb 2 года назад +2

    Wow! This explanation is pure gold! Thank you for spending time on making this video, really appreciate it!

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

      Glad it was helpful & that you liked it. Thank you 💙💙

  • @Armando-px8hi
    @Armando-px8hi Год назад

    What an great video, understood every word by just watching once. Althoug I am always having difficulties when the examples are on sales,invoices or payments but the one about npcs are the best one that I got. Thank you GIO, gonna search more about compostition vs inheritance.

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

    This is my 80th video! As I'm tending towards wanting to pat myself on the back, I can't help but imaging how much more the person who created from 1 to this 80th video I'm on all for us to learn pro bono should be patted. I appreciate Gio. God bless. About this lesson, when I first came across the inheritance lesson, I really thought it as a cool concept but as time went I saw how it can get complex very fast. So composition seems like it's easier to manage. But I've noted what you said about there still being some use cases for it. Thanks for this lesson Gio.

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

      That is awesome, you & anyone who watches this many videos deserve a big pat on the back. So congrats & great job, we can celebrate 100 videos together when I publish 100th video in the series :)

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

      @@ProgramWithGio Oh wow. It's going to get to 100? Goodie!!! Well done Gio! I look forward to that.

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

    Great video, love the "management has a great idea". It's legitimately a real world scenario. I never mind new ideas, but the worst is when there is a lack of foresight or when the requirements change half way through and there's "no time" to refactor properly.
    For use of composition, what's your thought on passing a reference versus the value (or) copy of the passed object. I've found in PHP it's smart enough to note recursion if it occurs when printing an object. In my case I was writing a lighting controller where a bridge has a list of bulbs, and the bulb is assigned to/requires a connection to the bridge. The bulbs have properties and methods and extend a base class, but some methods are proxied back to the bridge which also extends a base class (as you can have more than one type of bridge and type of light).
    Great video. Thanks!

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

      Thank you 🙌. I avoid references as much as possible, it makes code harder to debug & increases possibility of some hidden/magical bugs.

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

    Great Explanation

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

    As usually great video, please keep on going. I hope some day you'll get somewhere into CI/CD scope. Please be the first one talking about pro things 😃

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

      Thank you, I personally don't enjoy CI/CD stuff but we'll see, maybe one day. That being said we'll deploy the project that we are going to work on in this series

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

    Great teacher you are

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

    hahaha, family members, or even your cat. This guy is great at explaining and funny

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

    After your explanation and agreeing with you on the uncertaincy of the direction of future changes, I now see that in most cases composition would probably be the better solution. I've also seen factory based solutions in WordPress plugins, so perhaps there are more solutions, but this is one. Thanks.

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

      Yup, I used to use inheritance a lot in the past & it makes extension more difficult even though the keyword used there is "extends" :D. Composition is better in most cases.

  • @Mohsen-i5z
    @Mohsen-i5z Год назад

    great explanation

  • @Quynn-Oneal
    @Quynn-Oneal 2 года назад +1

    16:30 this was going great I wish you have converted this to composition example in the video too.

    • @ProgramWithGio
      @ProgramWithGio  2 года назад +3

      Fair. I do mention how you would implement it using composition, just make classes for each of those attributes & inject them in the constructor. It can be a good practice, you can share the code after and I can review

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

      @@ProgramWithGio This leads onto 'Dependency Injection containers?

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

      @@ryanqvincent144 yup

  • @osamaabdullah9444
    @osamaabdullah9444 2 года назад +3

    Great video, thank you 🙏
    can we implement composition without dependency injection? maybe with traits?

    • @ProgramWithGio
      @ProgramWithGio  2 года назад +10

      Thank you. You can use traits for sure, now does traits mean composition? That's debatable. In my opinion traits != composition because composition means class is composed of objects, when you use traits you dont have the reference to the object, it simply just pastes in the code in your main class. It is good for code re-use & allows for horizontal code re-use but I would not call it composition as tempting as it might sound.

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

    Thank you. You explained very accessibly.

  • @brunomiguelgroth
    @brunomiguelgroth 7 месяцев назад

    Nice! Thanks a lot.

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

    Thank you, Gio.

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

    Fantastic bro. I love minute of this video. A lot to grasp about PHP which i now realize its really a full fledge language and perhaps better than many I have seen. The main point here is we should never compare the likes of JS framework and language with PHP, especially 8.x. The only setback with PHP is that its performance concerns when used in large batch processing as compared to the likes of Java and Python. Appreciate your feedback on this. Tq.

    • @ProgramWithGio
      @ProgramWithGio  Год назад +3

      PHP's performance is not bad, it outperforms Python in some ways. There are many ways to improve performance of PHP & usually in most cases the bottleneck is the database & not PHP.

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

      @@ProgramWithGio Very true. We need to optimize the queries before injecting into the PHP code.

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

    Great examples, thanks!

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

    Thank you.

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

    A thousand thanks for these examples, btw will you show some examples how to work with cURL later in the course?

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

      Yup we'll cover curl and basics of APIs

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

    a tutorial on queues in php would be great.

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

      Will try to include that in this series

    • @Andu1991
      @Andu1991 2 года назад +2

      @@ProgramWithGio that would be fantastic. there's not much relevant info on youtube about this topic.

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

      @@ProgramWithGio also, you could cover multiple drivers (filesystem, db, fifo pipe).

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

      @@Andu1991 not sure I can do that in this series. Maybe separate short series

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

      @@ProgramWithGio you could create a course on it if you don't want to give it for free...each driver could have its own video.
      anyway, it was just a suggestion.
      thank you for your work so far.

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

    the wolf of wall street scene gave you a subscriber lmao

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

    Wow, I can't believe I've come this far! Master Gio, I have a question for you. I've watched all the lessons up to this point, and I've written every line of code you've written. I've completed all the exercises so far.
    However, I'm having trouble memorizing everything with 100% efficiency. Some information is starting to slip my mind. Since your course is the best, I don't see the point in watching other PHP courses (although I could be mistaken). So, after finishing your course and learning the basics of Laravel, I think it will be time to start applying for PHP developer jobs. As the next step in my PHP/some framework learning, I believe working with the original documentation would be beneficial.
    Could you give me some advice on how to properly work with documentation during my workflow? I mean, I don't think it's like reading Dostoevsky page by page, chapter after chapter (but I could be mistaken again). I think it would be a great idea for a new lesson: "How to effectively use PHP documentation to learn PHP the right way." 😄

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

      That's awesome, good job. You shouldn't memorize anything, cause then it's expected to forget things. I also don't remember a lot of the things all the time. The key thing is to look it up when in need. Once you are exposed to the idea and have practiced and know what it is about, when you come across it 3-4 months later it will kick in and come back to you from memory.
      As far as documentation, I wouldn't recommend just reading through all the documentation, instead you should read the pages of the things that you need for the project you are working on.

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

      @@ProgramWithGio thank you!

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

    Thanks, great examples and explanation. Where do traits fit in?

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

      Thank you. I replied to the other comment about traits so I'll copy it here: You can use traits for code re-use, now does traits mean composition? That's debatable. In my opinion traits != composition because composition means class is composed of objects, when you use traits you don't have the reference to the object, it simply just pastes in the code in your main class. It is good for code re-use & allows for horizontal code re-use but I would not call it composition as tempting as it might sound.

  • @jeloace
    @jeloace 7 месяцев назад

    Great video and topic.
    Question tho, does dependecy injection means composition? You where using DI when you make use of composition which makes composition looks like a "concept" and to "implement" it is by using DI, just like polymorphisms is the concept and interface is the implementation.

    • @ProgramWithGio
      @ProgramWithGio  7 месяцев назад +1

      DI is a way to implement/achieve composition.

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

    another amazing tuto :)

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

    amazing content!

  • @md.mustakimhayder6402
    @md.mustakimhayder6402 2 месяца назад

    Thanks for the video. It was preety amazing. So Composition and Dependency Injection meant to be the same, Am i right!

    • @ProgramWithGio
      @ProgramWithGio  2 месяца назад

      Thank you. Not really, dependency injection is a way to get composition.

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

    So, car and engine is composition. car and passengers is aggregation? car can't live without engine but passengers can come and go?

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

      Depends how you look at them but in a way yes. Think of aggregation as a container for associated objects.

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

    Nice video, you coulded explained traits in this video too.
    I know is not a big feature in PHP, but once I was trying to make most abstract classes for my models, puting all getter and setter in this classes, like
    class BaseModel
    {
    public function getId(): int
    {
    }
    //...
    }
    class DateTimeBaseModel extensa BaseModel
    {
    // Get set for created_at and updated_at
    }
    It works, until I need to chance a id collomn to bigint, and break all the inherance, I need to create new classes with return string for getId (of course, this was before PHP 8).
    So, a fill years ago I needed to upgrade PHP from 5.6 to 7.2, reading the broken changings, I learn traits, I think, this is a better solution, for this example.
    Like
    Trait GetterSetterIdInteger
    {
    private int $id;
    //Get set
    }
    class Model
    {
    use GetterSetterIdInteger;
    use GetterSetterDateTime;
    }

    • @ProgramWithGio
      @ProgramWithGio  2 года назад +3

      Thank you. There is a lesson about Traits in the second section. Traits don't really achieve the same thing as composition, yes it lets you reuse the code but that's about it. It shouldn't be used in place of composition in my opinion. It's better to pass down dependencies via constructor rather than include them within the same class using traits.

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

      ​​@@ProgramWithGio It's interesting, in your video game example I would definitly have gone with traits and interfaces.
      Like CanAttackTrait (with implementation) and CanAttackInterface for the public contract.
      This allows you to type hint in the functions with the interface while avoiding duplication of code. Even more in 8.1 with the intercetion type where we can say CanAttackInterface&CanMoveInterface.
      And that makes more sense in my opinion than having something like an AttackerService.
      What do you think? And why would you not call that composition ?
      Thanks for the videos, this is very interesting even for someone who has been developing in PHP professionally for several years like me.

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

      @@flo_111 Traits give you the feel of composition but essentially it just puts the code in the class, as far as testability goes its better to have dependencies injected in constructors to achieve true composition. Now it also depends on preference, Laravel likes to use traits to achieve composition & as long as its used properly I think its fine. I personally prefer dependencies injected in constructors. Interfaces + traits is not a bad option.

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

    Can you say dependency injection is the same as composition ? Or is there something else that sets them apart. Honestly never heard it being called composition.
    And what about traits? Don't they go against code duplication also? Couldn't you add attack to a trait and let it be used by the monsters and the pets?

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

      Composition is achieved by dependency injection. Of course you can instantiate the dependencies in constructor for example to achieve composition but dependency injection is better & we covered that earlier in this series.
      About the traits I'll paste in the answer I gave to others:
      You can use traits for code re-use, now does traits mean composition? That's debatable. In my opinion traits != composition because composition means class is composed of objects, when you use traits you don't have the reference to the object, it simply just pastes in the code in your main class. It is good for code re-use & allows for horizontal code re-use but I would not call it composition as tempting as it might sound.

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

    comming this far in this tutorial can i quickly learn codeignitor and start my journey of programmer or should i have to learn more.?

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

      You should be able to get started with a framework.

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

    I am here at video 80, 58 yet to go 🏃🏻‍♂🏃🏻‍♂

    • @ProgramWithGio
      @ProgramWithGio  8 месяцев назад +1

      wohoo, awesome job so far

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

      @@ProgramWithGio thank you for the awesome teaching 😊

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

    Remember Composition Over Inheritance !

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

    So you gave us a problem with the game objects and no solution? not the best of ways to teach.

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

      I showed 2 examples, not sure what you mean?

  • @janjetovicmladen
    @janjetovicmladen 3 месяца назад

    This is just a wrong use of methods like SalesTacCalculator. It should be trait, not a parent class.

    • @ProgramWithGio
      @ProgramWithGio  3 месяца назад

      Why **should** it be a trait? What's wrong with it being a class? Also note that this is just an example of inheritance vs composition lesson. Doing composition by injecting dependencies in constructor is the right way to do it instead of traits, makes writing tests easier.