Skip to content

Instantly share code, notes, and snippets.

@michaelsauter
Last active February 6, 2024 12:56
Show Gist options
  • Save michaelsauter/5501116 to your computer and use it in GitHub Desktop.
Save michaelsauter/5501116 to your computer and use it in GitHub Desktop.
Simple presenter pattern for Symfony2/Twig. Really useful to get some view logic out of the models and views into its own separate space.
<?php
namespace Acme\DemoBundle\Presenter;
class BasePresenter
{
protected $subject;
public function __construct($subject)
{
$this->subject = $subject;
}
public function __call($methodName, $arguments)
{
$methods = get_class_methods($this->subject);
if (in_array($methodName , $methods)) {
return call_user_func_array(array($this->subject, $methodName), $arguments);
} else {
throw new \Exception("No such method ".$methodName);
}
}
}
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Acme\DemoBundle\Entity\Person;
use Acme\DemoBundle\Presenter\PersonPresenter;
class DefaultController extends Controller
{
/**
* @Route("/hello/{name}")
* @Template()
*/
public function indexAction($name)
{
$person = new Person();
$person->setFirstName('Michael');
$person->setLastName('Sauter');
return array('person' => new PersonPresenter($person));
}
}
Hello {{ person.fullName }}! ({{ person.lastName }})
{# Output: "Hello Mr. Michael Sauter! (Sauter)" #}
<?php
namespace Acme\DemoBundle\Entity;
class Person {
// your model here
}
<?php
namespace Acme\DemoBundle\Presenter;
class PersonPresenter extends BasePresenter
{
public function getFullName()
{
return $this->getFirstName().' '.$this->getLastName();
}
public function getFirstName()
{
return 'Mr. '.$this->subject->getFirstName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment