1

In Joomla 3 I used the following code. What do I need to change to use it with Joomla 4?

<?php
define( 'DS', DIRECTORY_SEPARATOR );
$rootFolder = explode(DS,dirname(__FILE__));
   
//current level in diretoty structure
$currentfolderlevel = 1;

array_splice($rootFolder,-$currentfolderlevel);

$base_folder = implode(DS,$rootFolder);


if(is_dir($base_folder.DS.'libraries'.DS.'joomla'))   
{
   
   define( '_JEXEC', 1 );
   
   define('JPATH_BASE',implode(DS,$rootFolder));
   
   require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
        require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
        $userid='';

@$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
@$user =& JFactory::getUser();
$username = $user->get('username');

}
?>
1
  • Welcome at Joomla stackexchange. I've translated your question into English. Please only use English at Joomla.stackexchange.com. Thanks!
    – pe7er
    Commented Oct 2, 2023 at 14:03

1 Answer 1

1

The first thing you need to do is to replace the first part of your code that establishes the Site instance of Joomla 4. In this answer you will find sample code that provides for accessing the four modes of Joomla 4, Site, Admin, Cli and Api, How to create an instance of the Joomla CMS from the browser or the command line

In your example you appear to need the first group of settings in Part 1 of the example, to get the Site application instantiated.

Once you have the Joomla instance you can then use a number of different approaches to get the username.

To get the current user object as per your example

$user = Factory::getApplication()->getIdentity()

Introduced in Joomla 4.2 you can add the CurrentUserTrait to your class and use a simpler format of getCurrentUser() in code. The same Trait also allows you to setCurrentUser()

use Joomla\CMS\User\CurrentUserTrait;
....
use CurrentUserTrait;
....
$user = $this->getCurrentUser()

If you have the Id of a user you want you can use

use Joomla\CMS\User\UserFactoryInterface;
...
$userFactory = $container->get(UserFactoryInterface::class);
$user = $userFactory->loadUserById($id);

or you can use

$userFactory = $container->get('user.factory');
$user = $userFactory->loadUserById($id);

or similar to the Joomla 3 method

$user = Factory::getUser($id);

Once you have the user object in $user you can use

$username = $user->username;

to get what is needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.