Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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 in 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 create', self:: ADDRESS_ERROR_UNKNOWN_SUBCLASS); reading through it, if the class does not exist, throw a new exception address, along with the error code for unknown subclass. Save, then go to the demo source.
Instead of explicitly creating an address residence, use the factory method. Address::getInstance of (Address:: ADDRESS_TYPE_RESIDENCE); Save the demo, then return to your browser, and refresh. Everything should look the same. For further practice, switch the remaining explicit instantiations of address to use the factory method. Then, wrap the getInstance calls, and try catch blocks.
Get unlimited access to all courses for just $25/month.Become a member
61 Video lessons · 92183 Viewers
82 Video lessons · 104057 Viewers
71 Video lessons · 75379 Viewers
56 Video lessons · 106753 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.
Your file was successfully uploaded.