DEV Community

Cover image for Getting the current user's object - Current User Trait in Joomla 4.2+
Sergey Tolkachyov
Sergey Tolkachyov

Posted on

Getting the current user's object - Current User Trait in Joomla 4.2+

Traits are fragments of code that are disconnected from the context and can be used in a variety of places. They add their methods to your own classes. So, when developing extensions, sometimes you need to work with the current user of the site: is he a guest or an authorized one? If authorized, which access group does it belong to? Etc.

Starting with Joomla 4.2, the CurrentUserTrait trade appeared in the kernel, which adds 2 methods getCurrentUser() and setCurrentUser() to the class of your plugin, helper, etc. In the getter (getCurrentUser()) under the hood, it checks whether the current user is assigned and if not, it is obtained from the Application object.

How to use the CurrentUserTrait trait in Joomla?

use Joomla\CMS\User\CurrentUserTrait;

final class Wtcategory extends FieldsPlugin implements SubscriberInterface
{
     use DatabaseAwareTrait;
     use CurrentUserTrait;

   public function MyMethod()
   {
      $user = $this->getCurrentUser();
   }
}
Enter fullscreen mode Exit fullscreen mode

And thus, you can less monitor the relevance of the code base in this area, since the core functionality is used here.

Joomla Community resources

Top comments (0)