title: Design patterns for PHP - visitor pattern vs servant pattern
body: <p>I find these two patterns are similar (and the most of other behavioral patterns)</p>
  
  <p>visitor pattern,</p>
  
  <pre><code>interface Visitor 
  {
      public function visit(Visitable $Visitable);
  } 
  interface Visitable 
  {
      public function accept(Visitor $Vsitor);
  }
  class ConcreteVisitable implements Visitable
  {
      public $items = array();
  
      public function addItem($item)
      {
          $this-&gt;items[] = $item;
      }
  
      public function accept(Visitor $Vsitor)
      {
          $Vsitor-&gt;visit($this);
      }
  }
  class ConcreteVisitor implements Visitor 
  {
      protected $info;
  
      public function visit(Visitable $Visitable)
      {
          echo "Object: ", get_class($Visitable), " &lt;br/&gt;";
          $items = get_object_vars($Visitable)['items'];
  
          foreach ($items as $index =&gt; $value) {
              echo $index . ": ", $value, " &lt;br/&gt;";
          }
      }
  }
  // Usage example
  $ConcreteVisitable = new ConcreteVisitable();
  $ConcreteVisitor = new ConcreteVisitor();
  $ConcreteVisitable-&gt;addItem('item 1');
  $ConcreteVisitable-&gt;addItem('item 2');
  $ConcreteVisitable-&gt;addItem('item 3');
  $ConcreteVisitable-&gt;accept($ConcreteVisitor);
  </code></pre>
  
  <p>servant pattern,</p>
  
  <pre><code>// Servant.
  interface Servant
  {
      //  
  }
  
  // Servable. AKA Boss/ Master/ Authority
  interface Servable
  {
      //
  }
  
  // Concrete Servable.
  class ConcreteServable implements Servable
  {
      private $position;
  
      public function setPosition($position)
      {
          $this-&gt;position = $position . '&lt;br/&gt;';
      }
  
      public function getPosition()
      {
          return $this-&gt;position;
      }
  }
  
  // Concrete Servant.
  class ConcreteServant implements Servant
  {
      // Method, which will move Servable implementing class to position where.
      public function moveTo(Servable $Servable, $arg) 
      {
          // Do some other stuff to ensure it moves smoothly and nicely, this is
          // the place to offer the functionality.
          $Servable-&gt;setPosition($arg);
      }
  }
  
  $ConcreteServable = new ConcreteServable();
  $ConcreteServant = new ConcreteServant();
  
  $ConcreteServant-&gt;moveTo($ConcreteServable, 10);
  echo $ConcreteServable-&gt;getPosition();
  
  $ConcreteServant-&gt;moveTo($ConcreteServable, 20);
  echo $ConcreteServable-&gt;getPosition();
  </code></pre>
  
  <p>Can you tell the differences between them? (unless the servant pattern example is incorrect??)</p>