XF 2.0 Generate post reply with $message, $thread and $user

Marcus

Well-known member
I found this to be the nicest way to create a new post (not from visitor, but from a user). How can I set $user here, as the class is protected?
PHP:
/** @var \XF\Service\Thread\Replier $replier */
$replier = \XF::app()->service('XF:Thread\Replier', $thread);
$replier->setIsAutomated();
$replier->setUser($user); // protected class so it does not work
$replier->setMessage($message);
$post = $replier->save();

Is there a simpler way to achieve this? Writing the post directly to the entity along with thread_id miss stuff like position functions etc.
 
This is a deliberate design choice. It's possible to get into weird situations if the expected user changes part way through the request or you start the process with a different user and then somewhere else down the line it calls visitor and that ends up being your account rather than the user itself.

For this use case, though, we've got a special function which changes the visitor object to the specified user, runs your code, and then returns the visitor object back to your own:
PHP:
$post = \XF::asVisitor($user, function() use($thread, $message)
{
    /** @var \XF\Service\Thread\Replier $replier */
    $replier = \XF::app()->service('XF:Thread\Replier', $thread);
    $replier->setIsAutomated();
    $replier->setMessage($message);
    return $replier->save();
});
 
Back
Top Bottom