Topics

programming

php drupal scheme scheming macros design patterns da la

design

design css

random thoughts

scribbles

alter ego

other me 'em that link us my space me linked in

Collections

Programmable web
PHP design patterns

PHP Design Patterns

  • A catalogue of php design pattern shorts
    • Accumulator passing
    • Closure
    • Control abstraction
    • Coroutines (generator based)
    • Dynamic dispatch
    • Dynamic loading
    • Facade
    • Factory and Abstract Factory
    • Fluent Interfaces/ Method chaining
    • Generator (iterator protocol based)
    • Generic function
    • Hooks
    • Interpreter
    • Iterator (based on protocol method)
    • Lazy evaluation
    • Memoization
    • Nested scope
    • Observer
    • Partial Evaluation
    • Protocol method
    • Proxy
    • Singleton
    • State
    • Strategy Pattern
  • Models, records, databases, friends and foes

Similar things

  • Learning lessons from Lisp or patterns and languages in PHP
  • Emulating closures in PHP
  • Some ways to use saved state with closures in php
  • Scoped php functions or more ways to abuse php
  • PHP Design Patterns
  • Strategy Pattern
  • Memoization
  • Singleton
  • Factory and Abstract Factory
  • Facade

Home » PHP Design Patterns » A catalogue of php design pattern shorts

Accumulator passing

design patterns | php
Intent
Use of an accumulator variable to allow the finer control over the assembly of the final result of an algorithm
Motivation
We want to use method-chaining, but we need to return values from some of the methods
Implementation
Use an accumulator variable
Example
a simple IFS( iterative function system )
x(t+1) = x(t) + f[random(1..i)]( 1/(t+1) )
note: the implementation is quite naive and not foolproof at all.
<php
class example {
  private $ifs = array( 'sin', 'cos' );  

  function x( &$acc ) {
    $acc['t'] += 1;
    $acc['x'] = $acc['x'] + $this->ifs[ rand(0,1) ]( 1/ $acc['t'] );
    return $this;
  }
}

$ex = new example();

$something = array('t'=>0, 'x' => 0 );
$ex->x($something) -> x($something) -> x($something);
print 't: ' . $something['t'] . ' x: ' . $something['x'] . "\n";
?>
and when you run it:
vlado@cow:~/php design patterns$ php  php accumulator_passing.php
t: 3 x:1.34692254127
vlado@cow:~/php design patterns$ php accumulator_passing.php
t: 3 x: 1.64809122021
vlado@cow:~/php design patterns$ php accumulator_passing.php
t: 3 x: 2.66401049301
‹ A catalogue of php design pattern shortsupClosure ›
printer-friendly version | add new comment
Home » PHP Design Patterns » A catalogue of php design pattern shorts

dikini.net

spreading confusion by accident since 1970