Skip to content

Instantly share code, notes, and snippets.

@iamdey
Created April 12, 2012 13:57
Show Gist options
  • Save iamdey/2367472 to your computer and use it in GitHub Desktop.
Save iamdey/2367472 to your computer and use it in GitHub Desktop.
Mise en application du Patron Visiteur avec Doctrine2
<?php
namespace Entity;
/**
* Le livre est l'élément visité.
* De cette manière on peut lui apliquer des traitements sans affecter sa structure tout en gardant la séparation Modèle/Controlleur
*/
class Book implements \Reader\Element
{
//...
/**
* The part of Visitor Pattern
*
* @param Reader\Visitor $visitor
*/
public function accept(\Reader\Visitor $visitor)
{
$visitor->visit($this);
}
}
<?php
namespace Reader;
/**
* Description of BookVisitor
*/
class BookVisitor implements Visitor {
protected $book, $line = 0;
public function visit(Element $element)
{
$this->book = $element;
}
//...
}
<?php
namespace Reader;
/**
* Description of BookVisitor
*/
class BookVisitor implements Visitor {
//...
/**
* Example : this method does not impact Book structure
*
* read book content line by line
*
* @return string
*/
public function read()
{
$content = $this->book->getContent();
$a_line = explode("\n", $content);
if(!count($a_line))
{
throw new \RuntimeException('Where is the book?!');
}
if(isset($a_line[$this->line]))
{
$ret = $a_line[$this->line];
$this->line++;
return $ret;
}
return 'The End';
}
}
<?php
namespace Controller;
/**
* Description of Client
*/
class Client {
public function action()
{
//get the Book from Doctrine
// ...
$book = new \Entity\Book();
$book->setContent("#Hello world\n ## this line should not be read at the first time");
//
$visitor = new \Reader\BookVisitor();
$visitor->visit($book);
//Here we go
echo $visitor->read();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment