Adding Permissions Check to layout.html.php (PHP Novice To Ninja)

Hello,

I’m following along the the PHP Novice To Ninja book and adapting slightly for my own purposes.

I’m currently trying to make an admin button on the layout that isn’t visible to non-admins:

Layout.html.php

Blockquote

<!doctype html>
<html>

      // ...
      <ul>
  <li><a href="/">Home</a></li>
  <li><a href="/page/about">About</a></li>
  <li><a href="/blog/list">Blog List</a></li>
      <?php  if ($user->hasPermission(\Site\Entity\Author::ADD_BLOGS)): ?>
        <li><a href="/blog/addpage">Add a new blog</a></li>
        <?php else: ?>
          <p> You aren't an admin </p> // or more suitable message...
      <?php  endif; ?>

So far I can get it to work if you are logged in, but if you aren’t i get the following error:

Fatal error : Uncaught Error: Call to a member function hasPermission() on boolean in /home/vagrant/Code/Project/templates/layout.html.php:27 Stack trace: #0 /home/vagrant/Code/Project/classes/Ninja/EntryPoint.php(27): include() #1 /home/vagrant/Code/Project/classes/Ninja/EntryPoint.php(69): Ninja\EntryPoint->loadTemplate(‘layout.html.php’, Array) #2 /home/vagrant/Code/Project/public/index.php(10): Ninja\EntryPoint->run() #3 {main} thrown in /home/vagrant/Code/Project/templates/layout.html.php on line 27

I am trying to inject the permissions into the layout template in EntryPoint.php as follows:

Blockquote
echo $this->loadTemplate(‘layout.html.php’, [‘loggedIn’ => $authentication->isLoggedIn(),
‘user’ => $authentication->getUser(),
‘output’ => $output,
‘title’ => $title,
‘metaDescription’ => $metaDescription,
]);

I had previously also tried ‘user’ => $author, which is how the permissions are passed into the other templates. This didn’t work at all.

PHP thinks $user is a boolean. You probably need to figure out why. (Not logged in?)

Thanks. I’ll keep pondering it. I suspect I’m out of my depth here though, and will consider a less elegant solution

As a quick solution for now you could go with

if ($user && $user->hasPermission(\Site\Entity\Author::ADD_BLOGS))

That way if the $user is false, the second part of the statement isn’t even evaluated and you won’t get the error.

1 Like

Nice! Works a treat

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.