Skip to content

Instantly share code, notes, and snippets.

@dg
Created May 31, 2018 14:00
Show Gist options
  • Save dg/c4f323f8be94b2bf0ea47bcd4a42d899 to your computer and use it in GitHub Desktop.
Save dg/c4f323f8be94b2bf0ea47bcd4a42d899 to your computer and use it in GitHub Desktop.
Composing presenters without inheritance
<?php
// composing presenters without inheritance
// (requires nette/application 2.4.11)
trait RequireLoggedUser
{
public function injectRequireLoggedUser()
{
$this->onStartup[] = function () {
if (!$this->getUser()->isLoggedIn()) {
$this->redirect('Sign:in', $this->storeRequest());
}
};
}
}
trait AdminLayout
{
public function injectLayout(Model $model)
{
$this->onStartup[] = function () use ($model) {
$this->layout = 'admin.layout';
$this->template->menu = $model->getMenu();
};
}
}
class DashboardPresenter extends Nette\Application\UI\Presenter
{
use RequireLoggedUser;
use AdminLayout;
}
class SignPresenter extends Nette\Application\UI\Presenter
{
use AdminLayout;
}
@Tharos
Copy link

Tharos commented Jun 1, 2018

Myslím, že ani ty traity nejsou nutné:

abstract class Presenter extends \Nette\Application\UI\Presenter
{
	public function registerOnStartup(callable $action)
	{
		$this->onStartup[] = $action;
	}
}


class PresenterPermissionsChecker
{
	/**
	 * @var User
	 */
	private $user;
	
	public function __construct(User $user)
	{
		$this->user = $user;
	}
	
	public function checkPermissions(Presenter $presenter)
	{
		if (!$this->user->isLoggedIn()) {
			$presenter->redirect('Sign:in', $presenter->storeRequest());
		}
	}
}


class AdminLayoutInitializer
{
	/**
	 * @var Model
	 */
	private $model;


	public function __construct(Model $model)
	{
		$this->model = $model;
	}

	public function initializeAdminLayout(Presenter $presenter)
	{
		$presenter->setLayout('admin.layout');
		$presenter->getTemplate()->menu = $this->model->getMenu();
	}
}


class DashboardPresenter extends Presenter
{
}


class SignPresenter extends Presenter
{
}
services:
	- PresenterPermissionsChecker
	- AdminLayoutInitialized

	-
		class: DashboardPresenter
		setup:
			- registerOnStartup([@PresenterPermissionsChecker, checkPermissions])
			- registerOnStartup([@AdminLayoutInitialized, initializeAdminLayout])

	-
		class: SignPresenter
		setup:
			- registerOnStartup([@AdminLayoutInitialized, initializeAdminLayout])

@enumag
Copy link

enumag commented Jun 1, 2018

My solution would be marker interfaces or doctrine annotations on presenters and Symfony subscribers (using contributte dispatcher) to handle it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment