I'm developing code which will be responsible for creating new users and modifying existing ones via an API in a user management system. I have the authentication class developed, which handles authenticating the API user via username/password, and returns a cookie which gets stored as a property in the authentication object.

The cookie needs to be sent along with any API call, but I'm not sure of the best approach to structure this.

Do I inject the Authentication object into the multiple User classes responsible for modifying and creating users for them to call the Authentication->getCookie() method; or, is it best for each User class to instantiate the Authentication object and call the methods to authenticate and return the cookie; or is there a better method.

  • If those User classes only need the cookie, why not simply pass it in to them? Commented Jun 22, 2018 at 0:09

1 Answer 1


Cookies used to handle Session abstraction, not the User objects. You can store User object in Session. PHP has a good session management functions and a lot of session management libraries, you should not write your own. I use symfony http_foundation component for session management in my projects.

http://php.net/manual/en/session.examples.basic.php http://symfony.com/doc/master/components/http_foundation/sessions.html

Every user can have multiple sessions from different devices with the same credentials. I use many to one relation to store them in database (many Sessions to one User). Also you need to use strong random in cookies to prevent cookie spoofing, PHP can handle this part too.

Best practice: use community driven libraries based on builtin functions with strong protection algorithms.

Authentication class should be service(or factory) to manage Sessions and another class (Controller) to manage users. You should strongly separate this functions for good architecture. In my projects i use SessionManager, UserRepository and UserController classes for basic user management.

Further reading: RBAC / ACL. Good luck!

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.