How to pass data to @layout.latte
- TonnyVlcek
- Member | 31
Hey,
I have my “main” template @layout.latte and inside I'm trying to
display some information about user:
e.g. Name, which is easy to do: {$user->getIdentity()->name}
but what if I have to show for example name of a group the user is par of?
I can easily show that group's id (which is foreign key in database) using
{$user->getIdentity()->group_id}
but when I need to display
the name, I'm not sure how to do that :/
If it would have been a “normal” template I would use its presenter and
public function render<TemplateName>(){
$this->template->group_name = $this->groupRepository->getGroupName($group_id);
}
Do you have an idea how to do this with @layout or how to show the
name of the group using that global variable $user?
Thank you very much for your time :)
- TonnyVlcek
- Member | 31
Okay, I did this:
1. I injected my groupRepository to BasePresenter:
/** @var \Namespace\Model\GroupRepository @inject*/
public $groupRepository;
2. In method beforeRender I'm testing if user is logged in and if he is then
I'm getting informations about his group and passing them to variable
$groups
which becomes “global” variable for all my templates
(right?)
public function beforeRender()
{
if($this->user->isLoggedIn()){
$this->template->group = $this->groupRepository->getGroupById($this->user->id);
}
}
Now everything works how it's suppose to, but I feel like I kind of broke
the DI because now I can use $groupRepository
in all of my
presenters without injecting it from the model for each one and more over I can
use that “global” variable $group
in all of my templates
(whenever user is logged in).
Is all that alright, or I'm breaking some best practice conventions?
- David Kudera
- Member | 455
personally I would use inject*() methods in base presenters and injecting via constructor in their children. So no injecting to public properties with @inject annotation. But I know, that there are some people who will say that this is not good (and I don't know why ;-)
- greeny
- Member | 405
Well it often leads to long strips of code like
public function injectFoo(Foo $foo, Bar $bar, Baz $baz, SomeService $someService, UselessStuff $uselessStuf) {
$this->foo = $foo;
$this->bar = $bar;
$this->baz = $baz;
$this->someService = $someService;
$this->uselessStuff = $uselessStuff;
}
And you still have to define the properties (yes, you can have them protected or private now, but you still have public inject method), so it is much much longer than only adding @inject to property doc comment (which i personally add even for non-injected properties)