Factory Pattern - Object Oriented PHP Tutorial

Sdílet
Vložit
  • čas přidán 1. 12. 2019
  • Here we'll go over one of the most popular design patterns called the Factory Pattern.
    Download this video's files:
    / edit
    Upgrade your Clever Techie learning experience:
    / clevertechie
    ``````````````````````````````````````````````````````````````````````````````````````````````
    ( Website ) clevertechie.com - PHP, JavaScript, Wordpress, CSS, and HTML tutorials in video and text format with cool looking graphics and diagrams.
    ( CZcams Channel ) / clevertechietube
    ( Facebook ) / clevertechie
    ( Twitter ) / theclevertechie
    ``````````````````````````````````````````````````````````````````````````````````````````````
  • Jak na to + styl

Komentáře • 74

  • @burekmali6704
    @burekmali6704 Před rokem +4

    This is silly how simply and nicely he explained. This is exactly around the difficulty level I'm on right now. Cheers

  • @abdqz5370
    @abdqz5370 Před 3 lety +8

    after spending 2 days to get the notion of factory pattern you are the only one who give it to me as simple as possible and easy to understand. thank you so much bro i will follow your videos to get all the design pattern ..... thanks again :)

    • @clevertechie
      @clevertechie  Před rokem

      I'm glad to hear that brother! Breaking down complex concepts into simple, easy to follow steps and clear instructions are the core values of Clever Techie.

  • @ferchofff
    @ferchofff Před 4 lety +28

    That's not the factory pattern

    • @jamesfoo8999
      @jamesfoo8999 Před 3 lety +1

      There isn't a "the" factory pattern there are a few. This instantiates and returns an object so one can argue it's a factory by nature :)

    • @TV-xd1pb
      @TV-xd1pb Před 2 lety

      Well we can consider it is kind of "factory" pattern with simple and small usage for one class, or maybe "services" is more appropriate for that kind of usage.

  • @sudipto.m
    @sudipto.m Před 4 lety +1

    A very clean and precise one. Thank you for the great upload.

  • @TroyNiemeier
    @TroyNiemeier Před 4 lety +2

    I just saw your BR constant right away and thought, GENIUS!! I've been appending them to my troubleshooting/debugging output and that constant would make that SO MUCH simpler. (Now, on to watching the actual video lol)

    • @jamesfoo8999
      @jamesfoo8999 Před 3 lety +2

      You should avoid having things in code that aid debug like that. Object/Factory should just set and return data values. Let View handle how it's displayed with BR and hyphen etc.
      If you take the time to learn XDebug you wont look back. Is a learning curve to implement it, but honestly, just do it :)

  • @mansoorkochy
    @mansoorkochy Před 3 lety

    Great job dude, thank you
    keep up for more design patterns

  • @user-fb5eh4sk4m
    @user-fb5eh4sk4m Před 2 lety +1

    i dont know technical English but your video was undestand by me very easy, i am beginner in English,
    thank you very much for great work!

  • @fragxz
    @fragxz Před 4 lety

    Very nice Video. This one deserves more views!! Thanks

  • @LuisPerez-mw5kl
    @LuisPerez-mw5kl Před 2 lety +1

    Thanks for sharing, a simple and concrete explanation

  • @ashikmehermobin9926
    @ashikmehermobin9926 Před 2 lety +1

    Thank you... I think the double colon :: is scope resolution operator, which is used to call static methods and access static properties of a class

  • @kenjohnsiosan9707
    @kenjohnsiosan9707 Před 2 lety

    super clear and concise. impressive . thank you sir

  • @ziat1988
    @ziat1988 Před 3 lety +2

    I don't get the point using Factory in your example. Why using BookFactory::create($name,$author) instead new Book($name,$author)? It's the same purpose!!!

  • @souvikghosh6385
    @souvikghosh6385 Před 4 lety +15

    I was wondering why use the factory when you can create the object directly? Whats the idea behind using the factory, a particular use case would be great.

    • @TroyNiemeier
      @TroyNiemeier Před 4 lety +9

      The example isn't great as a realistic/practical use case.
      However, you could have the 'Factory' class be something more generic, like "DataService". Then that class would contain a number of static functions which expose different data service classes.
      E.g.
      public static function users() would instantiate a UserDataStore class.
      public static function books() would instantiate a BookDataStore class.
      public static function categories() would instantiate a CategoryDataStore class.
      And you could reference them as DataService::users() and DataService::books() and even chain another function call off of them because they return that object directly unlike new'ing up an object and having to put it into a variable before calling its methods.
      $user = DataService::users()->getById(123);
      $books = DataService::books()->getByAuthor('James A. Michener');
      $categories = DataService::categories()->getAll();
      These have their limitations, too, obviously, since they're more like one-offs. Though, the 'DataStore' classes could be implemented as Singletons, which would make them reusable without having to instantiate them in memory repeatedly. And maybe this isn't even technically a good example of the factor pattern, but it seems to be to me...
      I hope this gives you a better idea of how this can be used. The factory class should be a generic/abstract version of the classes that it is responsible for instantiating.

    • @stefan4800
      @stefan4800 Před 4 lety

      He doesn't understand the Factory Pattern. See my comment in the comment section for some rough explanation, to get a better idea.

    • @stefan4800
      @stefan4800 Před 4 lety +3

      @@TroyNiemeier Clever Techie doesn't understand the Factory Pattern, and his additional class is completely redundant. The first commentator has correct intuition.
      On the other had, your example is more of the Strategy Pattern. See my comment in the comment section which clarify the issue a little bit more, and give the rough explanation. The purpose of the Factory Pattern is to create a brand new object, but with the ability not just to instantiate a single class, but multiple classes.

    • @skaidans
      @skaidans Před 4 lety

      You are right!

    • @ApplicableProgramming
      @ApplicableProgramming Před 3 lety +1

      One way to recognize when you should use it is if you are about to create one object, and you see that you need to copy-paste a bunch of configuration parameters and other objects for that. Example image manipulation library with a lot of configs. You would wrap complex configuration for creating an object in a factory. Or, if you need to return specific object type based on some rules, those rules could be put into the factory. Example of choosing specific shopping provider based on product size and price, logic for deciding which shipping library you would just could be inside the factory

  • @sanj33v
    @sanj33v Před měsícem

    That heavy typewriter sound: mesmerizing. Can you mention the product maker and model?

  • @yumyumsauz
    @yumyumsauz Před rokem

    thank you for this m8

  • @MichelVersianiDev
    @MichelVersianiDev Před 2 lety

    Appreciate! :)

  • @adflyadfly4137
    @adflyadfly4137 Před rokem +1

    May i know what is advantage of using factory pattern?

  • @TheLordOfWolves
    @TheLordOfWolves Před 2 lety

    i'm still wondering why do you need the BookFactory class ? Why not write the create function in the Book class ? the you do $book1 = new Book($name, $author). What am i missing ? besides the fact that you are writing extra code.

  • @dfadfsdfsdsa4283
    @dfadfsdfsdsa4283 Před rokem

    I can not understand example, why do not create static method create in Book class. Why need factory ?

  • @augischadiegils.5109
    @augischadiegils.5109 Před 3 lety

    Thanks :)

  • @DarkGT
    @DarkGT Před 4 lety +2

    Cool. Can you cover more patterns?

  • @smailbenamar1448
    @smailbenamar1448 Před 4 lety

    Thanks, but what if we want to be able to create different types of books ?

    • @stefan4800
      @stefan4800 Před 4 lety

      See my answer in the comment section.

  • @fezanbhatti1292
    @fezanbhatti1292 Před 2 lety +1

    It's too simple but a factory design pattern does alot but not only limited to simply return class insurance.

  • @NedumEze
    @NedumEze Před 2 lety +3

    CleverTechie, you sure can simplify stuff, man. You made this strange concept look very simple. Thanks, Bro.
    But, why do we in PHP Community complicate stuff for ourselves?
    Does it not take less code to create my own Object from a class, than 'creating' a 'Factory' to do it?

    • @MrKenano99
      @MrKenano99 Před 2 lety +2

      Factory, is meant to use for a way far complex situations. though, this video great easy start.

    • @NedumEze
      @NedumEze Před 2 lety

      @@MrKenano99
      Obviously. I appreciate.

  • @keiradom6522
    @keiradom6522 Před 2 lety

    What is the Theme you are using? Please!!

  • @tubebuddy3297
    @tubebuddy3297 Před 4 lety

    Please upload c Sharp to learn

  • @hollydengesiz
    @hollydengesiz Před 4 lety

    Nice tutorial. I have a question about your development environment on Windows 10(I guess). Do you use Bash on Windows or WSL or Docker ? If you are using, can you make a video about it between 10 - 15 minute ?

  • @bevedel
    @bevedel Před 3 lety +1

    Thank you Clever Techie for your great explanation. but why we should use a factory design pattern? why is it useful?

    • @jamesfoo8999
      @jamesfoo8999 Před 3 lety

      Say you have an object class (entity, DTO, POPO etc). you pass the necessary things to a factory (data like username etc) and factory does all the things required to prepare the data to pass to the object to create a clean object.
      Then when you want to use the same object in a new place in your code, you just call the same factory passing in the values necessary, and the factory is already setup to do all the things to create the object.
      It makes reusing objects quick and easy. The example in the vid is way too simple to see when a factory can be of use (tho I use them always anyway for consistency, but that's me)

    • @ApplicableProgramming
      @ApplicableProgramming Před 3 lety

      One way to recognize when you should use it is if you are about to create one object, and you see that you need to copy-paste a bunch of configuration parameters and other objects for that. Example image manipulation library with a lot of configs. You would wrap complex configuration for creating an object in a factory. Or, if you need to return specific object type based on some rules, those rules could be put into the factory. Example of choosing specific shopping provider based on product size and price, logic for deciding which shipping library you would just could be inside the factory

  • @JacksonMarshal
    @JacksonMarshal Před 3 lety +1

    Why don't just create the book object directly instead of a middleman?

  • @domainsale3981
    @domainsale3981 Před 3 lety +1

    Its not a factory, it is not even a simple creating method. Factory assumes to be an abstract class with abstract creating method of objects implementing common interface

  • @exultomedia
    @exultomedia Před 3 lety

    Why you didn’t show the real benefits, and mix HTML view with simple classes? That should be in separate layer...
    However, thank you for this video. I’ll be watching your sutff :)

  • @angladephil
    @angladephil Před 4 lety

    And that s why we all love JS when dealing with objects creation/instanciation !!!!!

  • @groovebird812
    @groovebird812 Před 3 lety

    What is the advantage of this pattern? I think this is not a good example

  • @stefan4800
    @stefan4800 Před 4 lety +11

    He obviously doesn't understand the Factory Pattern. He is creating a class just in order to instantiate another class! LOL The purpose of the Factory Pattern is ability to dynamically instantiate multiple classes, depending on the circumstances. The book factory should instantiate not a book, which here yawn like an abstract class, but to instantiate for example HistoryBook, or ProgrammingBook, or CookingBook, and the code would be:
    class BookFactory {
    public function createABook($book) {
    return new $book;
    }
    }
    $bookFactory = new BookFactory();
    $historyBook = $bookFactory->createABook("HistoryBook");
    $programmingBook = $bookFactory->createABook("ProgrammingBook");
    etc, etc, etc... You get the idea.

    • @buchdev
      @buchdev Před 4 lety

      You obviously are wrong too, actually the factory must to implement an interface, as well its subclasses, and the factory Creator method has to be static. The products created has to implement another interface. That's is the right design pattern

    • @stefan4800
      @stefan4800 Před 4 lety

      @@buchdev Any pattern is an idea, it doesn't need to follow the same structure. Anyway, why the factory class would implement an interface? What you're actually saying is just another piling of unnecessary code, creating code just for creating code. You can, though, use an interface for the other classes, and inject the dependency into the create method. That's totally legit. I used pseudo-code to give the people a rough idea. Anyway, the create method doesn't need to be static (why would be? That's really just a personal preference), and implementing an interface for the factory class doesn't make any sense. It's totally redundant.
      Further, your terminology is really fuzzy? Products? You mean objects? Subbclasses? What's that? If the BookFactory and the books implement the same interface, they need to implement the same methods too, coming from the interface. That doesn't make any sense at all. But maybe I didn't understand you well.

    • @buchdev
      @buchdev Před 4 lety

      @@stefan4800 the factory interface is for some controller, or some dependency injection. "Product" is some alias for the object createds. I think factory method has to be static because you don't need instantiate the factory class to create another object, it's redundant

    • @stefan4800
      @stefan4800 Před 4 lety +1

      @@buchdev I used the pseudo code to give an idea what the Factory Pattern is (the ability to instantiate multiple different classes), but you could definitely use an interface and inject dependency into the create method and use polymorphism to instantiate the classes ("products" I guess) which implemented the interface. That would give a constraint, which could be desirable, so you could explicitly limit the use of the method and thus avoid possible misuse of the method, but for PHP that's not needed, you don't need to declare the type for the parameter. You absolutely need an interface (or an abstract class if you decide to use inheritance) if you use statically typed programming language like Java, which require the type for the parameter. In that kind of circumstances you definitely need an interface or an abstract class as a parameter.
      Regarding the static method, again, it's just a personal preference. Usually, it's recommended to avoid static methods to any cost. In this example it doesn't really matter, but many recommend to never use static methods whatsoever. I don't want to judge, but that's what programmers usually think about static methods. The only pattern where you absolutely need a static method is the Singleton, because in the Singleton you can't instantiate the class from the outside, so you would use the static method to access the object from the outside. But many people are calling this pattern an anti-pattern, so, yeah, the software is not just science but the art as well, and sometimes it's all in the eyes of the beholder.

    • @buchdev
      @buchdev Před 4 lety

      @@stefan4800 well, you're right with respect the static method of factory. I was just talking like I was programming in a container based framework such as Laravel. But at the end of the day, depends on the programmer to implement the pattern, however, there is no denying the fact that we have to follow some standards.

  • @mojtabavahdati7648
    @mojtabavahdati7648 Před 3 lety

    For a better explanation read this answer: stackoverflow.com/a/629006/9868445

  • @jamesfoo8999
    @jamesfoo8999 Před 3 lety +4

    I'm sorry but while this shows the basics of how to make a very simple factory, the design and other things are teaching newcomers very bad practices. Your intention may have been to just show the very basics, but it's not much more work to show 2 classes and not HTML in them, and show the data being returned and how to use the getters somewhere. Sometimes people take things literally, or if they learn badly from they start they adopt the bad habits and keep them.
    1.
    Never have View (BR and hyphen) in the backend. If I want to do something else with that data you stop me by forcing a BR and hyphen. What if I wanted to separate them with pipe "|" instead or something else, or display bookName in one part of the page and bookAuther further down? Object and factory in the backend should always simply return the data the object defines and let places that are concerned about display worry about hyphen and BR.
    Also, the BR is applied to every book, which means I have to fight a new line in my output after the last book is displayed.
    2.
    A file should never have 2 classes in. Argue all you want, there's no need for it. The factory and the object it creates are two separate concerns and should be in separate files - probably even separate DIRs and areas of the app entirely.
    3.
    Static methods have their place but should be very rare. There's no reason to use them here. Instead, dependency inject your factory into your controller constructor (or other class)
    and simply use it like: $book = $this->bookFactory->create('name', 'author')
    4.
    Why does your object getter decide to merge the two object properties into one? What if I need to show the two sets of data separately on the page in a list, or I only need one of them?
    You should honour the object's blueprint and have getters for both properties and let the factory return an instance of the object with public getter access to data on each property.
    I mean, you create it all this way through factory with separate property setting (via constructor) but then hinder usability by only having one getter for both sets of data.
    5.
    While arguably not part of this tutorial, your factory does no sanity checking. What if name or author are empty or numbers or an array? I mean type declaration (hint or docblock) would fix this. I know it's a basic tutorial, but to be honest, code as basic as this is not really showing anything other than a class that makes another. Factory (and object classes) deserve much more than this.
    6.
    Subjective but arguably makes easier to read code - there's no need for the word "book" on your object properties. The class is called book, this is generally cleaner:
    class Book {
    private $name;
    private $author;
    }
    And before a debate ensues about "name is ambiguous" it can't be as it's on "Book" class, so it's the book's name. "Author" by definition is a "writer of a book".

    • @clevertechie
      @clevertechie  Před 3 lety

      Thank you for your intelligent feedback.

    • @ApplicableProgramming
      @ApplicableProgramming Před 3 lety

      Your feedback is on the place, but it is in practice not possible to show some concept and example, and cover all good practices of programming without making ridiculously long videos, or confusing people who watch the video, or making the video very boring (or all of it). There is always the balancing act of doing it all

    • @arun.sekher
      @arun.sekher Před rokem +2

      This is an invaluable comment. Thank you so much for taking your time to write it. The whole purpose of 'design patterns' to make the codebase more maintainable and easy to understand following 'SOLID' principles. People literally catch bad practices form these kinds videos, I've seen a person commenting in this very video that the use of 'BR' was a 'GENIUS' solution whereas it is a bad practice when it comes to codebase maintainability as pointed out by @James Foo. Use of single class per file is something that could have been easily achieved while making this video, avoiding static method and using DI too was.

  • @Tyantreides
    @Tyantreides Před 3 lety +1

    Nice to follow but.....
    What i liked to see was the reason why i should use this.
    In your example the factory is totaly unnessesary. You do nothing i can not provide with the original Book Clas itself too.
    I could simply Get an Instance of the book via "new Book('title','author')" as well. So in this example there is no difference in using a factory. Only mor code to write.

    • @ApplicableProgramming
      @ApplicableProgramming Před 3 lety

      One way to recognize when you should use it is if you are about to create one object, and you see that you need to copy-paste a bunch of configuration parameters and other objects for that. Example image manipulation library with a lot of configs. You would wrap complex configuration for creating an object in a factory. Or, if you need to return specific object type based on some rules, those rules could be put into the factory. Example of choosing specific shopping provider based on product size and price, logic for deciding which shipping library you would just could be inside the factory

  • @petori
    @petori Před 3 lety +2

    The fake factory you have written is useless. You could just move the create method to the book class.

    • @jamesfoo8999
      @jamesfoo8999 Před 3 lety +1

      Yeah don't do that shit. That's worse than a barebones factory that people seem to dislike and say is pointless.

    • @arun.sekher
      @arun.sekher Před rokem

      Yes, you could have and that's when the codebase become too tightly coupled and you start repeating yourself again (against DRY and SOLID principles) when you later create say an 'AudioBook' and then 'eBook' classes and want a way to instantiate that in your app and so on... 😊

  • @relaxationtube2388
    @relaxationtube2388 Před rokem

    Don't put html design in your class

  • @kr0n2600
    @kr0n2600 Před 4 lety +3

    this concept is pointless...

    • @jamesfoo8999
      @jamesfoo8999 Před 3 lety

      Interesting and highly informative opinion. Thanks, very useful.

    • @dannyhardy3295
      @dannyhardy3295 Před 2 lety

      I agree, I dont believe this is a great example of the factory design pattern, you may as well just create a new book, the factory class is pointless

  • @wiedens-justociurlizza7766
    @wiedens-justociurlizza7766 Před 9 měsíci

    Collague ALL is ok, although that is NOT FACTORY PATTERN, is false! that is a SIMPLE factory method, yes SIMPLE! i invite all here to study Factory Pattern, why this is SIMPLE Factory Pattern? because: 1) We do not specify any Interface (BookInterface); 2) Neither, Factories (pBookFactory [phisical book] || eBookFactory [e-book]) 3) We use STATIC METHOD working with a SIMPLE object(), I'm from Peru, i'm web exporter, I could TEACH FREE whatever wants