1

In Joomla 3.x I used to create a user object with

$user = clone(JFactory::getUser());

(which I would then bind to an array of data, and then call save() on it), but JFactory::getUser() is deprecated now.

What is the new way of creating a new blank user object?

2

1 Answer 1

5
Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById(0);

Joomla uses this line for creating an empty User object around line 287 in ..\libraries\src\User\User.php

// If the $id is zero, just return an empty User.
// Note: don't cache this user because it'll have a new ID on save!
if ($id === 0) {
    return Factory::getContainer()->get(UserFactoryInterface::class)->loadUserById($id);
}

You would need to add the appropriate statements for Factory and UserFactoryInterface in your code to get the object from the container by adding 'Use' statements, or use the following:

$user = \Joomla\CMS\Factory::getContainer()->get('user.factory')->loadUserById(0);
4
  • Terry, I'll leave the acceptance of the edit to you. Commented Jun 3, 2023 at 3:37
  • Good answer Irata, I have not checked this part yet in Joomla 4. However, it shows that Joomla still has design problems or questionable parts. My question would be, when I see this kind of code, why the Container needs a Factory to get an Interface and then a product (in this case, a User object). Sensibly, for me, it should look in the most complicated way, something like: $app->getUserFactoryInterface()->create(User); something of this sort…But anyway, we can always complicate things, and later someone can work on simplifying them…
    – Zollie
    Commented Jun 8, 2023 at 14:16
  • @Zollie I just found that since Joomla 4.2 you can do a simple $this->getCurrentUser() to get the User object by adding a 'use Joomla\CMS\User\CurrentUserTrait;' statement to your class. It is already available in BaseDatabaseModel and HtmlView classes.
    – Irata
    Commented Jun 15, 2023 at 10:09
  • Yes, I have also checked these few days ago and there are few other useful, short approaches too as I saw. So things are moving and improving :)
    – Zollie
    Commented Jun 16, 2023 at 7:48

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.