Issuing a redirect from a Joomla module

2019-04-30 08:12发布

问题:

I am not really familiar with Joomla but I have been tasked with writing a module which functionality is irrelevant to the question.

One of the requirements is that if the module is loaded, it should check if the user is logged in and if not - redirect him into a specific URL.

After some searching I came up with something like this, but it's obviously not a working answer:

$user =& JFactory::getUser();

if (!$user->id) {
    include_once JPATH_COMPONENT . DIRECTORY_SEPARATOR . "controller.php"; // assuming com_content
    $contentController = new ContentController();
    $link = JRoute::_("my url");
    $contentController->setRedirect($link);
    return;
}

I think the problem lies in getting to the controller. Creating a new controller certainly isn't the way to go. Is there a way to get the current controller from a Joomla module and the issue a redirect?

Thank you for any answers.

回答1:

i call this static function in each of my controllers construct

static function forceLoggedIn(){


    $user = JFactory::getUser();

        if($user->guest||$user->id == 0)
        {
            $error = JText::_('YOU MUST BE LOGGED IN');
            //base xkè altrimenti andrebbe in loop di redirect
            JFactory::getApplication()->redirect(JURI::base(), $error, 'error' );
            return false;
        }
    }