Welcome to the Question2Answer Q&A. There's also a demo if you just want to try it out.
0 votes
298 views
in Plugins by
I have a tiny plugin that provides 3 widgets.

Each widget must identify the user. He can be anonymous or guest.

That is why I check his id by:

        $userid = qa_get_logged_in_userid();
        $cookieid = isset($userid) ? qa_cookie_get() : qa_cookie_get_create();
       // ...

I do this in all 3 widgets.

Can't I do it centralized? Call a layer or something beforehand, store this data (just PHP, no database) and then access it by each widget?

Thanks for your help.
Kai
Q2A version: 1.7 beta
by
PS: Or can I just call qa_cookie_get_create(); in a layer (overriding the doctype, the earliest function). And then use $cookieid=qa_cookie_get(); whereever I want?

1 Answer

0 votes
by

What exactly do you need the cookieid for?

As for qa_get_logged_in_userid, it will cache the user the first time they are fetched, so no matter how many times you call it, it will only ever run one query.
by
I am tracking special user interactions with each question (not the default q2a actions like answer, comment etc.). This data gets saved in a separate db table which also holds cookieid and userid so that I can identify the user.

The widgets display previous interactions with those questions to the user, and need to identify him.

I solved it now by calling a layer, overriding doctype, and setting the cookie there if !isset($userid). Then in the widgets I only use qa_cookie_get(); which seems to work.
by
Yes for getting and setting cookies this must be done before any content is loaded so perhaps using a layer is a good idea. BTW pupi has submitted a nice pull request which adds an "initialize" function to the base theme, so that you can put this kind of stuff in there which is a better idea than using the doctype() function.

Another option in some situations would be to set a global variable for the data and each time the widget is called, check if the variable is set. Using globals isn't usually a good idea but it'll work here.
by
Thanks for letting me know about the "initialize" function. Will have a look and update my dev environment :)

Yep, I am trying to avoid globals. Gives me still kind of uncertainty to use them. Probably because I don't understand the scope and the per user effect completely. E.g. I would like to store the login state of a user globally in a plugin, but my feeling tells me I shouldn't.
...