SocialEngine Tutorial – Creating widgets for user profiles, getting the subject rather than the viewer information

I’ve been working on creating a widget for a user’s profile however I’ve needed to find out who I’ve been viewing in order to select the correct data.

I made a post about getting user details here however it only told you how to get the current viewer’s data. In this post we’ll be fetching the data for the current person being viewed by the user.

Lets say we have 2 users – alice and bob. We have a widget that fetches a list of websites that the user has viewed recently.

When Alice looks on Bob’s profile we need to run a query which uses Bob’s user_id so we can go and fetch the data about him and display the results to Alice.

What we have here is a viewer -> subject relationship whereby a viewer (Alice) is looking at the subject (Bob) and we need his ID rather than Alice’s (the viewer’s) id.

In order to get the current subject’s user details we need to do 2 things;

First things first, we need to check that we have a subject otherwise our page will error;

Engine_Api::_()->core()->hasSubject();

If this evaluates to true then we can do the following;

Engine_Api::_()->core()->getSubject();

Now the complete code to get the current subject’s user_id is as follows;

if(Engine_Api::_()->core()->hasSubject()){
    $user_id = Engine_Api::_()->core()->getSubject()->getIdentity());
} else {
    echo 'no subject on this page';
}

If you want to know what methods are available for the subject object you can call the ‘get_class_methods()’ function on the subject;

print_r(get_class_methods(Engine_Api::_()->core()->getSubject()));