Using the factory method pattern


show more Using the factory method pattern provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP show less
please wait ...

Using the factory method pattern

The second design pattern I am going to demonstrate is the factory method. The factory method is useful for creating objects without having to specify the class. Sound familiar? Let's look at the Address class. Open the Address class now, and take a look at the Load and Instance methods. In particular, notice the way that the returned address_type_id specifies the name of the class to be created in getInstance(). However, as it's currently written, it will fail if it doesn't get the right address type. Let's improve on getInstance() to throw an exception, instead of crashing out. First, create a new constant with an error code. Const ADDRESS_ERROR_UNKNOWN_SUBCLASS = 1001. I am going to go to the getInstance() method, and add a check to see if the class exists, before I instantiate it. I'll use the class_exists method, which returns a boolean. If not (!class_exists [$class_name]), throw new ExceptionAddress ('Address_subclass not found, cannot cre...

Using the factory method pattern
Video duration: 1m 51s 1h 57m Intermediate Updated Apr 10, 2013

Viewers:

Using the factory method pattern provides you with in-depth training on Developer. Taught by Jon Peck as part of the Object-Oriented Programming with PHP

Subject:
Developer
Software:
PHP
Author:
please wait ...