DEV Community

Discussion on: Design Patterns in PHP 8: Factory method

Collapse
 
otsch profile image
otsch

I'm not sure if this is actually an example for the factory method pattern.
Wikipedia says:

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

en.wikipedia.org/wiki/Factory_meth...

In the example you just instantiate the classes Redis and Mysql via their constructor. Using the factory method pattern I think you'd rather have something like a DatabaseFactory with methods redis and mysql that'll create and return those objects.

Collapse
 
zhukmax profile image
Max Zhuk

Hi, otsch.
I see, It looks like wrong using pattern just because I called abstract and concrete factory classes without "factory" word. If you look closer wikipedia php-example you see that.
But using "factory" word in classes names can make my article clearly. Thank you, I'll add it.

Collapse
 
suckup_de profile image
Lars Moelleken • Edited

Maybe you can also update the CartModel example code, this still use the old class names Redis and Mysql.

PS: here are also some nice exmaples refactoring.guru/design-patterns/f...

Thread Thread
 
zhukmax profile image
Max Zhuk

Thx, did it

Collapse
 
otsch profile image
otsch

I think you renamed the classes Redis and Mysql to RedisFactory and MysqlFactory and forgot to rename it in the CartModel class. But I'd rather revert naming those classes Factories because they as a whole aren't Factory classes.

Besides that I just got what the factory method in the example is: the getDataBase() method, right? It's true that it creates an instance of a class without knowing the concrete implementation from where you call it. As you can guess from my comment I was expecting and looking for the factory method in the wrong place.

After all I think it's a nice code example but I'm not sure if readers get what the factory method pattern is about. Maybe you can make it a bit clearer what the actual factory method is, and maybe tell a little bit about the pattern in general?

Collapse
 
maymeow profile image
May Meow

Another nice examples of design patterns are here

designpatternsphp.readthedocs.io/e...

For factory method here: designpatternsphp.readthedocs.io/e...