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()));

SocialEngine Tutorial – Getting the current user’s id and data

When you load any view inside your website you should always have an object named $viewer().
Here are some useful things you can find out in your view using the viewer object;

Get the current viewier’s Id

$this->viewer()->getIdentity();

Get the current viewier’s name

$this->viewer()->getTitle();

Get the current viewier’s profile URL

$this->viewer()->getHref();

Check if current user is an admin (return is either 1 or 0, true or false)

$this->viewer()->isAdmin();

If you want to be able to do the same thing within your controller rather than your view you can also use

Get current viewer’s identity

Engine_Api::_()->user()->getViewer()->getIdentity();

On a side note if you ever need to know whats being loaded in your view just print_r out the view object. However I find it extremely useful to call get_class_methods() on the object so that you can see what you can do with it;

echo '<pre>';
print_r(get_class_methods($this->viewer()));
echo '

‘;

(get rid of the backslash, had to include it to stop my pre tags messing up!