SlideShare a Scribd company logo
1 of 66
Download to read offline
Better than Ad-hoc
                           How to Make Things Suck (Less)




Monday, August 13, 2012
Monday, August 13, 2012
SAURON, THE DARK LORD
Monday, August 13, 2012
I’ll leave what happens
         next to the imagination.


Monday, August 13, 2012
Monday, August 13, 2012
Seriously though...



Monday, August 13, 2012
What are patterns?



Monday, August 13, 2012
- Repeatable solutions to common design problems




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names

    - Essential for framework and library sustainability




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names

    - Essential for framework and library sustainability

    - Rules can be bent




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names

    - Essential for framework and library sustainability

    - Rules can be bent

    - The result of good initial design or necessary refactoring




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names

    - Essential for framework and library sustainability

    - Rules can be bent

    - The result of good initial design or necessary refactoring

    - Will change the way you think about programming




Monday, August 13, 2012
- Repeatable solutions to common design problems

    - Standardized names

    - Essential for framework and library sustainability

    - Rules can be bent

    - The result of good initial design or necessary refactoring

    - Will change the way you think about programming

    - Will lead the people to the promised land


Monday, August 13, 2012
Classical Patterns



Monday, August 13, 2012
Classical Patterns
    - First real work done in the 1980s




Monday, August 13, 2012
Classical Patterns
    - First real work done in the 1980s

    - GOF released in 1994 (“Design Patterns, Elements of
    Reusable Object Oriented Software”)




Monday, August 13, 2012
Classical Patterns
    - First real work done in the 1980s

    - GOF released in 1994 (“Design Patterns, Elements of
    Reusable Object Oriented Software”)

    - Much writing and evolution since




Monday, August 13, 2012
Classical Patterns
    - First real work done in the 1980s

    - GOF released in 1994 (“Design Patterns, Elements of
    Reusable Object Oriented Software”)

    - Much writing and evolution since

    - Important, but not sacred


Monday, August 13, 2012
Monday, August 13, 2012
Quick Overview



Monday, August 13, 2012
Quick Overview
    - Creational patterns deal with how objects are created




Monday, August 13, 2012
Quick Overview
    - Creational patterns deal with how objects are created

    - Structural patterns deal with how objects are composed




Monday, August 13, 2012
Quick Overview
    - Creational patterns deal with how objects are created

    - Structural patterns deal with how objects are composed

    - Behavior patterns deal with how objects are utilized




Monday, August 13, 2012
Creational Patterns



Monday, August 13, 2012
abstract class AbstractFactory()
       {
         protected function shared(){...//shared}

           abstract public function doSomething(){}
       }

       class ConcreteFactory extends AbstractFactory(){
         public function doSomething(){..//unique}
       }

       $factory = new ConcreteFactory();

Monday, August 13, 2012
class FactoryMethod()
       {
         public function __construct(){...//shared}

           public function __call($class, $args){
             if ( class_exists($class) ) {
                return new $class($args);
             }
             throw new Exception(“$class does not exist.”);
           }
       }

       $factory = new FactoryMethod();
       $factory->WidgetA(array(‘config’ => ‘item’));
Monday, August 13, 2012
class ObjectPool()
       {
         public $register = array(
            ‘Foo’,
            ‘Bar’
         );

           public function __construct($register = false){
             ...//register objects passed in constructor, build pool
           }
       }

       $pool = new ObjectPool();
       $pool->Foo->DoSomething();
Monday, August 13, 2012
class Singleton()
       {
         public $instance = false;

           private function __construct($register = false){...}

           public function __clone(){//throw error}

           public static function instance(){
             if( ! self::$instance )
                self::$instance = new Singleton();
             return self::$instance;
           }
       }

       $s = Singleton::instance();
Monday, August 13, 2012
class Multiton()
       {
         public $instances = array();

           private function __construct(){...}

           public static function instance($name = ‘default’){
             if( ! self::$instances[$name] )
                self::$instances[$name] = new Multiton();
             return self::$instances[$name];
           }
       }

       $a = Multiton::instance(‘foo’);
       $b = Multiton::instance(‘bar’);
Monday, August 13, 2012
class Director()
       {
         public function __construct(){...}

           public function build($obj){
             ...//shared logic for manipulating object
           }
       }

       class ConcreteBuilder()
       {
         public function __construct(){...}
       }

       $director = new Director();
       $object = $director->build(new ConcreteBuilder())
Monday, August 13, 2012
class ConcretePrototype()
       {
         public $obj = false;

           public $baz = “something cool”

           public function __construct(){
             $this->obj = new Foo();
           }
       }

       $c = new ConcretePrototype();
       $p = clone $c; //shallow copy
       $x = unserialize(serialize($p)); //deep copy
Monday, August 13, 2012
Structural Patterns



Monday, August 13, 2012
class Foo()
       {
         public function __construct(){}
       }

       class FooAdapter()
       {
         public static function __callStatic($method, $args){
             //Requests to Foo are translated. Foo is called and
             response is returned.
         }
       }

       $response = FooAdapter::FooMethod($args);
Monday, August 13, 2012
interface BridgeImplementation(){
         public function doMethod($args);
       }

       class ConcreteA implements BridgeImplmentation(){
         public function doMethod($args){...}
       }

       abstract class Foo{...}

       class RefinedFoo extends Foo{...}

       $foo = new RefinedFoo($args, new ConcreteA());
       $result = $foo->doMethod($args);
Monday, August 13, 2012
class Compositte
       {
         public $nodes = array();

            public $properties = array();

            public function __construct($name, $properties){...}

            public function node(Composite $node);
       }

       $nodeA = new Composite(array(‘bah’ => ‘test’));
       $nodeB = new Composite(array(‘var’ => ‘haha’));
       $nodeB->node(new Composite(array(‘baz’ => ‘bar’));
       $nodeA->node($nodeB);
Monday, August 13, 2012
class Facade
       {
         public static function simpleMethod(){
           $foo = HiddenByFacadeA::foo();
           $baz = HiddenByFacadeB::bar($foo);
           return HiddenByFacadeB::doh($baz);
         }
       }

       class HiddenByFacadeA{...}

       class HiddenByFacadeB{...}

       $simple = Facade::simpleMethod();
Monday, August 13, 2012
class RemoteProxy
       {
         private static function request($method, $args){
           ../maybe some curl stuff here
           return $remoteServiceCallResult;
         }

            public static function __callStatic($method, $args){
              return self::request($method, $args);
            }
       }

       $result = RemoteProxy::someMethod();

Monday, August 13, 2012
class Filter
       {
         public static function applyOne($data, $filter){
           return ( $filter instanceof Closure )
             ? $filter($data) : self::$filter($data);
         }

            public static function applyAll($d, array $filters){
                foreach($filters as $f) $data = self::applyOne($d, $f);
                return $data;
            }
            ...
       }

       $r = Filter::applyAll($data, array(‘foo’, function(){...}));
Monday, August 13, 2012
Behavioral Patterns



Monday, August 13, 2012
class ChainOfResponsibility()
       {
         public $next = false;

            public function setNext($chained){
              static::$next = $chained;
            }
       }

       class ChainableA extends ChainOfResponsibility(){...}
       class ChainableB extends ChainOfResponsibility(){...}
       class ChainableC extends ChainOfResponsibility(){...}

       new ChainableA()->setNext(
          new ChainableB()->setNext(new ChainableC())
       );
Monday, August 13, 2012
class ObserverA extends Observer(){...}

       class ObservedFoo extends Observed()
       {
         public $observers = array(‘ObserverA’, ‘ObserverB’);

            public function __call($method, $args){
               ...//do something
               $this->notifyObservers($this->observers);
            }
       }

       $subject = new ObservedFoo();
       $subject->doSomething();
Monday, August 13, 2012
class Invoker extends Observer {...}

       interface Command(){...}

       class CommandA implements Command(){...}

       $executeLater = Invoker::schedule(
          “condition”,
          “someMethod”,
          new CommandA(array(‘foo’ => ‘bar’))
       );


Monday, August 13, 2012
abstract class AbstractInterpreter(){...}

       class InterpreterA extends AbstractInterpreter{...}

       interface Expression(){...}

       class String implements Expression{...}

       class Number implements Expression{...}

       class Command implements Expression{...}
       ...

       $interpreted = new Interpreter()->interpret
       (“var=doBaz.foo[tabba|too|3|a] && abacadbra[var]”)
Monday, August 13, 2012
interface Iterator {...}

       abstract class MyIterator implements Iterator(){...}

       class Util extends MyIterator(){...}

       $iterator = new Util();

       while( $iterator->valid() )
       {
         $iterator->current(); //Do something with this
         $iterator->next();
       }

Monday, August 13, 2012
class CareTaker{...}

       trait Memento
       {
         public function recordState(){
           CareTaker::recordState(__CLASS__, serialize($this));
         }

            public function restoreState(){...}
       }

       class Foo
       {
         use Memento; ...
       }
Monday, August 13, 2012
interface Strategy{...}

       class ConcreteStrategy implements Strategy {...}

       class Context
       {
         public $strategy = false;

            public function __construct($strategy){...}

            public function applyStrategy(){...}
       }

       $context = new Context( new ConcreteStrategy() );
Monday, August 13, 2012
abstract class AbstractTemplate
       {
         ...//shared implementation, enforced methods
       }

       class ConcreteTemplateA extends AbstractTemplate
       {
         ..//concrete (custom) implementation
       }

       $template = new ConcreteTemplateA( );


Monday, August 13, 2012
Patterns on the Web



Monday, August 13, 2012
Patterns on the Web
    - Once upon a time, nobody was thinking about software
    design patterns in web apps




Monday, August 13, 2012
Patterns on the Web
    - Once upon a time, nobody was thinking about software
    design patterns in web apps

    - Desktop and mobile computing now often dependent
    on remote (web) services




Monday, August 13, 2012
Patterns on the Web
    - Once upon a time, nobody was thinking about software
    design patterns in web apps

    - Desktop and mobile computing now often dependent
    on remote (web) services

    - Now web apps / server apps can be wayyy complicated



Monday, August 13, 2012
Patterns on the Web
    - Once upon a time, nobody was thinking about software
    design patterns in web apps

    - Desktop and mobile computing now often dependent
    on remote (web) services

    - Now web apps / server apps can be wayyy complicated

    - Patterns help us apply systematic rigor to the complexity

Monday, August 13, 2012
Patterns in CodeIgniter



Monday, August 13, 2012
class Blog extends CI_Controller
       {
         public function __construct(){...}

            public function index(){
              ...
              $this->load->view(‘blog/index’);
            }
       }

       class BlogModel extends CI_Model
       {
         public function __construct(){...}

            public function posts(){...}
       }
Monday, August 13, 2012
class CI_Hooks {...}

       $config['enable_hooks'] = TRUE;

       $hook['pre_controller'] = array(
          'class' => 'MyClass',
          'function' => 'Myfunction',
          'filename' => 'Myclass.php',
          'filepath' => 'hooks',
          'params' => array('beer', 'wine', 'snacks')
       );

       $EXT->call_hook('pre_controller');

Monday, August 13, 2012
class CI_Controller {
         private static $instance;

            public function __construct(){...}

            public static function &get_instance(){...}
       }

       function &get_instance()
       {
       	

 return CI_Controller::get_instance();
       }

Monday, August 13, 2012
class CI_Controller{...
         public function __construct()
         {
           self::$instance =& $this;

                foreach (is_loaded() as $var => $class) {
                  $this->$var =& load_class($class);
                }

                $this->load =& load_class(‘Loader’, ‘core’);

               $this->load->initialize();
               log_message(‘debug’, ‘Controller Class Initialized’);
            }...
       }
Monday, August 13, 2012
//registry
       function &is_loaded($class = '')
       {
       	

 static $_is_loaded = array();

       	

     if ($class !== '')
       	

     {
       	

     	

 $_is_loaded[strtolower($class)] = $class;
       	

     }

       	

 return $_is_loaded;
       }

Monday, August 13, 2012
function &load_class($class, $directory = 'libraries',
       $prefix = 'CI_'){
       	

 static $_classes = array();
             ...
       	

 // Does the class exist? If so, we're done...
       	

 if (isset($_classes[$class])){
       	

 	

 return $_classes[$class];
       	

 }
             ...
       	

 // Keep track of what we just loaded
       	

 is_loaded($class);
             ...
       	

 $_classes[$class] = new $name();
       	

 return $_classes[$class];
       }
Monday, August 13, 2012
//Index.php (FrontController)

       	

 // Load CI core files
            // Set some constants
       	

 // Pass on the request




Monday, August 13, 2012
if ( ! file_exists($driver_file))
       {
          show_error('Invalid DB driver');
       }

       require_once($driver_file);

       // Instantiate the DB adapter
       $driver = 'CI_DB_'.$params['dbdriver'].'_driver';
       $DB = new $driver($params);


Monday, August 13, 2012
Reading List
           - “Design Patterns: Elements of Reusable Object-
             Oriented Software” by Erich Gamma, Richard
               Helm, Ralph Johnson and John Vlissides

           - SourceMaking.com and Design Patterns: Simply

                 - “Use of Design Patterns in PHP-based Web
                  Application Frameworks” by Andris Paikens

Monday, August 13, 2012
Reading List
       - Everything on Wikipedia about Design Patterns

                 - “CodeComplete 2: A practical handbook of
                  software construction” by Steve McConnel

                          - “The Meditations” by Marcus Aurelius

    - “Politics and the English Language” George Orwell

Monday, August 13, 2012
Me
                                @calvinfroedge

                          http://www.calvinfroedge.com

                            github.com/calvinfroedge




Monday, August 13, 2012
Fin



Monday, August 13, 2012

More Related Content

What's hot

“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonfRafael Dohms
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalFredric Mitchell
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascriptShah Jalal
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and SanityJimKellerES
 
Enyo for JS Nerds - Austin JS Meetup, April 2012
Enyo for JS Nerds - Austin JS Meetup, April 2012Enyo for JS Nerds - Austin JS Meetup, April 2012
Enyo for JS Nerds - Austin JS Meetup, April 2012Ben Combee
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceAnanda Kumar HN
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)Ananda Kumar HN
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Francois Marier
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 

What's hot (20)

“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
 
Enyo for JS Nerds - Austin JS Meetup, April 2012
Enyo for JS Nerds - Austin JS Meetup, April 2012Enyo for JS Nerds - Austin JS Meetup, April 2012
Enyo for JS Nerds - Austin JS Meetup, April 2012
 
ES6 at PayPal
ES6 at PayPalES6 at PayPal
ES6 at PayPal
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
 
BVJS
BVJSBVJS
BVJS
 
Hidden rocks in Oracle ADF
Hidden rocks in Oracle ADFHidden rocks in Oracle ADF
Hidden rocks in Oracle ADF
 
Presentation1
Presentation1Presentation1
Presentation1
 
The jQuery Divide
The jQuery DivideThe jQuery Divide
The jQuery Divide
 
jQuery
jQueryjQuery
jQuery
 
C++ prgms 4th unit Inheritance
C++ prgms 4th unit InheritanceC++ prgms 4th unit Inheritance
C++ prgms 4th unit Inheritance
 
C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)C++ prgms 5th unit (inheritance ii)
C++ prgms 5th unit (inheritance ii)
 
Entity api
Entity apiEntity api
Entity api
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
 
Jquery
JqueryJquery
Jquery
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 

Similar to Ciconf 2012 - Better than Ad-hoc

What is this DI and AOP stuff anyway...
What is this DI and AOP stuff anyway...What is this DI and AOP stuff anyway...
What is this DI and AOP stuff anyway...Richard McIntyre
 
PHP Loves MongoDB - Dublin MUG (by Hannes)
PHP Loves MongoDB - Dublin MUG (by Hannes)PHP Loves MongoDB - Dublin MUG (by Hannes)
PHP Loves MongoDB - Dublin MUG (by Hannes)Mark Hillick
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven DevelopmentAugusto Pascutti
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof MenżykPROIDEA
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles Anis Ahmad
 
3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)drupalconf
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...James Titcumb
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopPublicis Sapient Engineering
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Stephan Schmidt
 

Similar to Ciconf 2012 - Better than Ad-hoc (20)

What is this DI and AOP stuff anyway...
What is this DI and AOP stuff anyway...What is this DI and AOP stuff anyway...
What is this DI and AOP stuff anyway...
 
Scala 101
Scala 101Scala 101
Scala 101
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Scala 101-bcndevcon
Scala 101-bcndevconScala 101-bcndevcon
Scala 101-bcndevcon
 
PHP Loves MongoDB - Dublin MUG (by Hannes)
PHP Loves MongoDB - Dublin MUG (by Hannes)PHP Loves MongoDB - Dublin MUG (by Hannes)
PHP Loves MongoDB - Dublin MUG (by Hannes)
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
OOP
OOPOOP
OOP
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
Be pragmatic, be SOLID
Be pragmatic, be SOLIDBe pragmatic, be SOLID
Be pragmatic, be SOLID
 
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
4Developers 2015: Be pragmatic, be SOLID - Krzysztof Menżyk
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Revisiting SOLID Principles
Revisiting  SOLID Principles Revisiting  SOLID Principles
Revisiting SOLID Principles
 
3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)3 reasons to contribute to drupal florian loretan (eng)
3 reasons to contribute to drupal florian loretan (eng)
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5Go OO! - Real-life Design Patterns in PHP 5
Go OO! - Real-life Design Patterns in PHP 5
 

Recently uploaded

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 

Recently uploaded (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 

Ciconf 2012 - Better than Ad-hoc

  • 1. Better than Ad-hoc How to Make Things Suck (Less) Monday, August 13, 2012
  • 3. SAURON, THE DARK LORD Monday, August 13, 2012
  • 4. I’ll leave what happens next to the imagination. Monday, August 13, 2012
  • 7. What are patterns? Monday, August 13, 2012
  • 8. - Repeatable solutions to common design problems Monday, August 13, 2012
  • 9. - Repeatable solutions to common design problems - Standardized names Monday, August 13, 2012
  • 10. - Repeatable solutions to common design problems - Standardized names - Essential for framework and library sustainability Monday, August 13, 2012
  • 11. - Repeatable solutions to common design problems - Standardized names - Essential for framework and library sustainability - Rules can be bent Monday, August 13, 2012
  • 12. - Repeatable solutions to common design problems - Standardized names - Essential for framework and library sustainability - Rules can be bent - The result of good initial design or necessary refactoring Monday, August 13, 2012
  • 13. - Repeatable solutions to common design problems - Standardized names - Essential for framework and library sustainability - Rules can be bent - The result of good initial design or necessary refactoring - Will change the way you think about programming Monday, August 13, 2012
  • 14. - Repeatable solutions to common design problems - Standardized names - Essential for framework and library sustainability - Rules can be bent - The result of good initial design or necessary refactoring - Will change the way you think about programming - Will lead the people to the promised land Monday, August 13, 2012
  • 16. Classical Patterns - First real work done in the 1980s Monday, August 13, 2012
  • 17. Classical Patterns - First real work done in the 1980s - GOF released in 1994 (“Design Patterns, Elements of Reusable Object Oriented Software”) Monday, August 13, 2012
  • 18. Classical Patterns - First real work done in the 1980s - GOF released in 1994 (“Design Patterns, Elements of Reusable Object Oriented Software”) - Much writing and evolution since Monday, August 13, 2012
  • 19. Classical Patterns - First real work done in the 1980s - GOF released in 1994 (“Design Patterns, Elements of Reusable Object Oriented Software”) - Much writing and evolution since - Important, but not sacred Monday, August 13, 2012
  • 22. Quick Overview - Creational patterns deal with how objects are created Monday, August 13, 2012
  • 23. Quick Overview - Creational patterns deal with how objects are created - Structural patterns deal with how objects are composed Monday, August 13, 2012
  • 24. Quick Overview - Creational patterns deal with how objects are created - Structural patterns deal with how objects are composed - Behavior patterns deal with how objects are utilized Monday, August 13, 2012
  • 26. abstract class AbstractFactory() { protected function shared(){...//shared} abstract public function doSomething(){} } class ConcreteFactory extends AbstractFactory(){ public function doSomething(){..//unique} } $factory = new ConcreteFactory(); Monday, August 13, 2012
  • 27. class FactoryMethod() { public function __construct(){...//shared} public function __call($class, $args){ if ( class_exists($class) ) { return new $class($args); } throw new Exception(“$class does not exist.”); } } $factory = new FactoryMethod(); $factory->WidgetA(array(‘config’ => ‘item’)); Monday, August 13, 2012
  • 28. class ObjectPool() { public $register = array( ‘Foo’, ‘Bar’ ); public function __construct($register = false){ ...//register objects passed in constructor, build pool } } $pool = new ObjectPool(); $pool->Foo->DoSomething(); Monday, August 13, 2012
  • 29. class Singleton() { public $instance = false; private function __construct($register = false){...} public function __clone(){//throw error} public static function instance(){ if( ! self::$instance ) self::$instance = new Singleton(); return self::$instance; } } $s = Singleton::instance(); Monday, August 13, 2012
  • 30. class Multiton() { public $instances = array(); private function __construct(){...} public static function instance($name = ‘default’){ if( ! self::$instances[$name] ) self::$instances[$name] = new Multiton(); return self::$instances[$name]; } } $a = Multiton::instance(‘foo’); $b = Multiton::instance(‘bar’); Monday, August 13, 2012
  • 31. class Director() { public function __construct(){...} public function build($obj){ ...//shared logic for manipulating object } } class ConcreteBuilder() { public function __construct(){...} } $director = new Director(); $object = $director->build(new ConcreteBuilder()) Monday, August 13, 2012
  • 32. class ConcretePrototype() { public $obj = false; public $baz = “something cool” public function __construct(){ $this->obj = new Foo(); } } $c = new ConcretePrototype(); $p = clone $c; //shallow copy $x = unserialize(serialize($p)); //deep copy Monday, August 13, 2012
  • 34. class Foo() { public function __construct(){} } class FooAdapter() { public static function __callStatic($method, $args){ //Requests to Foo are translated. Foo is called and response is returned. } } $response = FooAdapter::FooMethod($args); Monday, August 13, 2012
  • 35. interface BridgeImplementation(){ public function doMethod($args); } class ConcreteA implements BridgeImplmentation(){ public function doMethod($args){...} } abstract class Foo{...} class RefinedFoo extends Foo{...} $foo = new RefinedFoo($args, new ConcreteA()); $result = $foo->doMethod($args); Monday, August 13, 2012
  • 36. class Compositte { public $nodes = array(); public $properties = array(); public function __construct($name, $properties){...} public function node(Composite $node); } $nodeA = new Composite(array(‘bah’ => ‘test’)); $nodeB = new Composite(array(‘var’ => ‘haha’)); $nodeB->node(new Composite(array(‘baz’ => ‘bar’)); $nodeA->node($nodeB); Monday, August 13, 2012
  • 37. class Facade { public static function simpleMethod(){ $foo = HiddenByFacadeA::foo(); $baz = HiddenByFacadeB::bar($foo); return HiddenByFacadeB::doh($baz); } } class HiddenByFacadeA{...} class HiddenByFacadeB{...} $simple = Facade::simpleMethod(); Monday, August 13, 2012
  • 38. class RemoteProxy { private static function request($method, $args){ ../maybe some curl stuff here return $remoteServiceCallResult; } public static function __callStatic($method, $args){ return self::request($method, $args); } } $result = RemoteProxy::someMethod(); Monday, August 13, 2012
  • 39. class Filter { public static function applyOne($data, $filter){ return ( $filter instanceof Closure ) ? $filter($data) : self::$filter($data); } public static function applyAll($d, array $filters){ foreach($filters as $f) $data = self::applyOne($d, $f); return $data; } ... } $r = Filter::applyAll($data, array(‘foo’, function(){...})); Monday, August 13, 2012
  • 41. class ChainOfResponsibility() { public $next = false; public function setNext($chained){ static::$next = $chained; } } class ChainableA extends ChainOfResponsibility(){...} class ChainableB extends ChainOfResponsibility(){...} class ChainableC extends ChainOfResponsibility(){...} new ChainableA()->setNext( new ChainableB()->setNext(new ChainableC()) ); Monday, August 13, 2012
  • 42. class ObserverA extends Observer(){...} class ObservedFoo extends Observed() { public $observers = array(‘ObserverA’, ‘ObserverB’); public function __call($method, $args){ ...//do something $this->notifyObservers($this->observers); } } $subject = new ObservedFoo(); $subject->doSomething(); Monday, August 13, 2012
  • 43. class Invoker extends Observer {...} interface Command(){...} class CommandA implements Command(){...} $executeLater = Invoker::schedule( “condition”, “someMethod”, new CommandA(array(‘foo’ => ‘bar’)) ); Monday, August 13, 2012
  • 44. abstract class AbstractInterpreter(){...} class InterpreterA extends AbstractInterpreter{...} interface Expression(){...} class String implements Expression{...} class Number implements Expression{...} class Command implements Expression{...} ... $interpreted = new Interpreter()->interpret (“var=doBaz.foo[tabba|too|3|a] && abacadbra[var]”) Monday, August 13, 2012
  • 45. interface Iterator {...} abstract class MyIterator implements Iterator(){...} class Util extends MyIterator(){...} $iterator = new Util(); while( $iterator->valid() ) { $iterator->current(); //Do something with this $iterator->next(); } Monday, August 13, 2012
  • 46. class CareTaker{...} trait Memento { public function recordState(){ CareTaker::recordState(__CLASS__, serialize($this)); } public function restoreState(){...} } class Foo { use Memento; ... } Monday, August 13, 2012
  • 47. interface Strategy{...} class ConcreteStrategy implements Strategy {...} class Context { public $strategy = false; public function __construct($strategy){...} public function applyStrategy(){...} } $context = new Context( new ConcreteStrategy() ); Monday, August 13, 2012
  • 48. abstract class AbstractTemplate { ...//shared implementation, enforced methods } class ConcreteTemplateA extends AbstractTemplate { ..//concrete (custom) implementation } $template = new ConcreteTemplateA( ); Monday, August 13, 2012
  • 49. Patterns on the Web Monday, August 13, 2012
  • 50. Patterns on the Web - Once upon a time, nobody was thinking about software design patterns in web apps Monday, August 13, 2012
  • 51. Patterns on the Web - Once upon a time, nobody was thinking about software design patterns in web apps - Desktop and mobile computing now often dependent on remote (web) services Monday, August 13, 2012
  • 52. Patterns on the Web - Once upon a time, nobody was thinking about software design patterns in web apps - Desktop and mobile computing now often dependent on remote (web) services - Now web apps / server apps can be wayyy complicated Monday, August 13, 2012
  • 53. Patterns on the Web - Once upon a time, nobody was thinking about software design patterns in web apps - Desktop and mobile computing now often dependent on remote (web) services - Now web apps / server apps can be wayyy complicated - Patterns help us apply systematic rigor to the complexity Monday, August 13, 2012
  • 55. class Blog extends CI_Controller { public function __construct(){...} public function index(){ ... $this->load->view(‘blog/index’); } } class BlogModel extends CI_Model { public function __construct(){...} public function posts(){...} } Monday, August 13, 2012
  • 56. class CI_Hooks {...} $config['enable_hooks'] = TRUE; $hook['pre_controller'] = array( 'class' => 'MyClass', 'function' => 'Myfunction', 'filename' => 'Myclass.php', 'filepath' => 'hooks', 'params' => array('beer', 'wine', 'snacks') ); $EXT->call_hook('pre_controller'); Monday, August 13, 2012
  • 57. class CI_Controller { private static $instance; public function __construct(){...} public static function &get_instance(){...} } function &get_instance() { return CI_Controller::get_instance(); } Monday, August 13, 2012
  • 58. class CI_Controller{... public function __construct() { self::$instance =& $this; foreach (is_loaded() as $var => $class) { $this->$var =& load_class($class); } $this->load =& load_class(‘Loader’, ‘core’); $this->load->initialize(); log_message(‘debug’, ‘Controller Class Initialized’); }... } Monday, August 13, 2012
  • 59. //registry function &is_loaded($class = '') { static $_is_loaded = array(); if ($class !== '') { $_is_loaded[strtolower($class)] = $class; } return $_is_loaded; } Monday, August 13, 2012
  • 60. function &load_class($class, $directory = 'libraries', $prefix = 'CI_'){ static $_classes = array(); ... // Does the class exist? If so, we're done... if (isset($_classes[$class])){ return $_classes[$class]; } ... // Keep track of what we just loaded is_loaded($class); ... $_classes[$class] = new $name(); return $_classes[$class]; } Monday, August 13, 2012
  • 61. //Index.php (FrontController) // Load CI core files // Set some constants // Pass on the request Monday, August 13, 2012
  • 62. if ( ! file_exists($driver_file)) { show_error('Invalid DB driver'); } require_once($driver_file); // Instantiate the DB adapter $driver = 'CI_DB_'.$params['dbdriver'].'_driver'; $DB = new $driver($params); Monday, August 13, 2012
  • 63. Reading List - “Design Patterns: Elements of Reusable Object- Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides - SourceMaking.com and Design Patterns: Simply - “Use of Design Patterns in PHP-based Web Application Frameworks” by Andris Paikens Monday, August 13, 2012
  • 64. Reading List - Everything on Wikipedia about Design Patterns - “CodeComplete 2: A practical handbook of software construction” by Steve McConnel - “The Meditations” by Marcus Aurelius - “Politics and the English Language” George Orwell Monday, August 13, 2012
  • 65. Me @calvinfroedge http://www.calvinfroedge.com github.com/calvinfroedge Monday, August 13, 2012