Suicidal Pattern and Observers

June 17th, 2009 | by Ozgur Cem Sen |

The other day, I came up with a sort of bizarre idea of exception handling in PHP. Not so interestingly it may be, you’ll find out as you read, this design pattern is called “Suicidal Pattern“.

The idea is around an object throwing itself as “throw self” (actually throw this) and it’s own handler catching and handling and announcing to its observers.

And here it goes:

The code is not commented at all. The semantics is left to the readers’ imagination :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php

interface IObserver
{
  function onDeceased( $deadPerson );
}

interface IObservable
{
  function addObserver( $observer );
}



abstract class ALife extends Exception implements IObservable
{
    protected $message;
    protected $code;
    private $stalkers = array();

    public static function handleException($exception)
    {
        foreach( $exception->stalkers as $obs )
        {
            $obs->onDeceased( $exception );
        }
    }  

    public static function handleError($errno, $errstr, $errfile, $errline)
    {
        echo "Error No:  $errno, $errstr in $errfile line $errline";
    }  
   
    public function addObserver( $observer )
    {
        $this->stalkers []= $observer;
    }
}


class Life extends ALife implements IObserver
{
    private $name;
   
    public function __construct($name)
    {
        $this->name = $name;
        set_exception_handler(array('ALife', 'handleException'));
        set_error_handler(array('ALife', 'handleError'));
    }
   
    public function getName()
    {
        return $this->name;
    }

    public function endLife()
    {
        $this->message = 'fooo happened. and i must throw myself!';
        throw $this;
    }  
   
   
    public function onDeceased( $deadPerson )
    {
        try
        {
            echo $this->getName() . ' says ' . $deadPerson->getName() . ' lived an exceptional life';  
            throw $this;
        }
        catch (Exception $e)
        {
            echo 'stop bringing out the dead!';
        }
    }
}




$me = new Life('Cem');
$other = new Life('Some Other Person');
$me->addObserver($other);
$me->endLife();
  1. 2 Responses to “Suicidal Pattern and Observers”

  2. By Concerned Citizen on Jun 18, 2009 | Reply

    endLife() probably needs a rand(). Every so often it should return botchedAttempt = true, with a GOTO rehab clause and no get out of jail free card.

  3. By Concerned Citizen's Neighbor on Jun 18, 2009 | Reply

    I would like to recommend that an announceFuneral method be added to the Life class. Family and friends might like to *observe* and pay their respects.

Sorry, comments for this entry are closed at this time.