Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // V pointcutu definujeme, jaké třídy a metody má chceme naším aspektem "obalit". Obalení probíhá následně automaticky na úrovni DI containeru
- class LayoutFillerPointcut implements PointcutInterface {
- private $annotationReader;
- public function __construct(Reader $annotationReader) {
- $this->annotationReader = $annotationReader;
- }
- /*
- * Třídou LayoutFillerInterceptor obalujeme pouze třídy, jejich název končí na "Controller"
- */
- public function matchesClass(ReflectionClass $class) {
- return preg_match('~Controller$~', $class->getName());
- }
- /*
- * U "Controller" tříd aplikujeme metodu LayoutFillerInterceptor::intercept() na výstup:
- * 1) všech veřejných metod
- * 2) a zároveň metod, které mají v PHPDocs anotaci @FillLayout
- */
- public function matchesMethod(ReflectionMethod $method) {
- return
- $method->isPublic() &&
- $this->annotationReader->getMethodAnnotation(
- $method,
- 'Templating\Annotation\FillLayout'
- ) !== null;
- }
- }
- // LayoutFillerInterceptor obaluje třídy, u jejichž metod použijeme anotaci
- class LayoutFillerInterceptor implements MethodInterceptorInterface {
- private $annotationReader;
- private $container;
- public function __construct(Reader $annotationReader, ContainerInterface $container) {
- $this->annotationReader = $annotationReader;
- $this->container = $container;
- }
- /*
- * Metoda intercept() se aplikuje na výstup všech metod controllerů,
- * které obsahují @FillLayout anotaci (viz LayoutFillerPointcut)
- */
- public function intercept(MethodInvocation $controllerInvocation) {
- $templateVariables = $controllerInvocation->proceed();
- // přečteme anotaci, abychom získali název služby,
- // do které máme poslat výstup z volané metody controlleru
- /** @var FillLayout $annotation */
- $annotation = $this->annotationReader->getMethodAnnotation(
- $invocation->reflection,
- 'Templating\Annotation\FillLayout'
- );
- // v našem příkladu např. layout_filler.front
- $layoutFillerServiceName = $annotation->getServiceId();
- /** @var ILayoutFiller $layoutFiller */
- $layoutFiller = $this->container->get($layoutFillerServiceName);
- return $layoutFiller->setDefaultVariables($templateVariables);
- }
- }
- // Na závěr samotná jednoduchá definice anotace @FillLayout
- namespace Templating\Annotation;
- /**
- * @Annotation
- */
- class FillLayout {
- private $serviceId;
- public function __construct($options) {
- $this->serviceId = $options['service'];
- }
- public function getServiceId() {
- return $this->serviceId;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement