Design patterns: singletons

Singleton classes basically mean there is only one object class of a certain type running at all times. That could be used to store Global variables, for example. The way to implement it on PHP: class Preferences {     private $props = array();     private static $instance;     private function __construct() { }  // By […]

Design patterns: Composition and Inheritance (Strategy pattern)

Instead of creating child classes, you create a new tree of classes and move some of the functionality away from the main tree. You connect the trees via object creation, meaning some of the classes in one tree contrain objects with the other classes type. The advantage is that the trees are more specialized in […]

PHP interfaces

Interfaces are pure class templates that define functionality. It can contain properties and methods, but no method implementation. See the example below: interface Chargeable {     public function getPrice(); } So any class that implements this interface, will look something like this: class ShopProduct implements Chargeable {     // …     public function getPrice() { […]

OOP Best Practices and architecture

When creating classes, make a really general abstaction of the object you have in mind (usually an abstact class or interface), and then start working your way down to the specifics using inheritance, encapsulation and polymorphism. For example: to create a book object for an ecommerce site, create something like Product / Item / Books / […]

PHP instanceof to determine what kind of object we are dealing with

Example: class ShopProductWriter { public function write( $shopProduct ) { if ( ! ( $shopProduct instanceof CdProduct ) && ! ( $shopProduct instanceof BookProduct ) ) { die( “wrong type supplied” ); } $str = “{$shopProduct->title}: ” . $shopProduct->getProducer() . ” ({$shopProduct->price})n”; print $str; } }

MVC architecture

It is a design pattern that helps separate business logic from input and presentation, making it easier to maintain each one of those components independenly from each other. Model: it is the representation of data according to the application’s function or domain. It includes data access but it is not exclusively the retrieval or records. […]