Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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

This comment has been minimized.

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
You can’t perform that action at this time.