Search code examples
phpcodeigniterhmvcion-authcodeigniter-hmvc

Check if user is logged in - Ion Auth with Codeigniter HMVC


I've just switched from standard CI to Codeigniter Skeleton with HMVC. I'm trying to check if the user is logged in and display a menu item according to the status.

This code works on standard CI with ion_auth:

<ul class="nav navbar-nav pull-right">
<!-- User Tab -->
<?php if (!$this->ion_auth->logged_in()): ?>
    <li><a href="<?php echo site_url('auth/login'); ?>">Log in</a></li>
<?php else: ?> 
    <li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
        My Account <b class="caret"></b>
        </a>
        <ul class="dropdown-menu">
            <li><a href="<?php echo site_url('auth/logout'); ?>">Logout</a></li>
       </ul>
    </li>
<?php endif ?>
</ul>

If I use this with HMVC and ion_auth, I get the following error:

A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI::$ion_auth

Filename: MX/Loader.php

Line Number: 279

Fatal error: Call to a member function logged_in() on a non-object in C:\wamp\www\myapp\application\views\header.php on line 59

I've tried adding the ion_auth library to the autoload.php, but then I get a "Cannot redeclare class Ion_auth" error when clicking on the link or using any of the ion_auth routes.


Solution

  • I solved this by removing the following line from application/modules/auth/controllers/auth.php

    $this->load->library('authentication', NULL, 'ion_auth'); 
    

    And adding 'ion_auth' to the autoload.php

    I can now use the ion_auth functions in both controllers and view and the default auth routes like /auth/login/ still work as expected.