Archive - Originally posted on "The Horse's Mouth" - 2012-12-16 08:10:27 - Graham Ellis
Part 2 of my "PHP revision" for delegates who will be doing substantial project / systems work. (Part 1 [here]).
Object Oriented techniques give programming languages a practical expandability and robsutness as applications written in them grow in size. Code is separated into classes, with each class dealing with a particular type of data and containing the logic to deal with that data. Classes can be tested individually, they can be written so that they only implement appropriate methodology on the data (i.e. only do sensible things), and can be based on one another so that similar types of data handlers can share common logic.
In OO programming, PHP style:
• Define your own data types
• create data elements of your type ("objects") with a special function ("constructor")
• Only provide the functions ("methods") that make sense
• Keep the code in a separate area called a "class" (usually a separate file)
• All data access should be via methods
There's a first really simple revision object program [here] in PHP.
Going a little further:
• Use private, protected and public declarations to enforce access
• Use one class on which to base another to save coding
• Let PHP work out which method to run to save lots of conditionals (Polymorphism)
• Design patterns are standardised ways of doing things to make your code consistent and followable
• Static methods are utility functions in the class as a whole
• A common design pattern is a factory method which translates data into objects
• See also the cached design pattern which means we can be more effcient by saving too many recomputes.