Search code examples
phpdesign-patternssingletonfactorystrategy-pattern

Clarification on design patterns in PHP


I know very little about design patterns out there. In fact i never worked with one yet, as i always went for raw coding. But i think its time to enrich my knowledge on design patterns out there. Specially i want to know more about Factory, Singleton & Strategy design patterns. I googled about them of course but I still not clear about their differences, how to implement them etc.

If anyone can suggest me some good document where i can read much more, that would be very much helpful.

Thanks in advance for helping.


Solution

  • https://sourcemaking.com/design_patterns is a very helpful website, with a lot of explanations and code samples, including PHP ones. I added very short summaries in my own words below. Disclaimer: because they summaries are very short, the may not be very accurate, but give you an idea on how the patterns compare.

    Factory Method: https://sourcemaking.com/design_patterns/factory_method
    In short: you have a separate class that is responsible for creating instances of a certain class. This is to make sure that a class is always constructed 'in the right way'.

    Singleton Pattern: https://sourcemaking.com/design_patterns/singleton
    In short: only one instance of a singleton class is possible, the class itself has a static class variable that stores the instance, and a static method that returns the stored instance, or create one if it is not yet created.

    Strategy Pattern: https://sourcemaking.com/design_patterns/strategy
    In short: if there are multiple ways to solve some problem, provide a set of classes that each contain one implementation to the problem and let the client decide which implementation to use.