I’ve written a user class based on other supposedly high quality, secure classes I found online (although mixing some of them since, from what I’ve learned, none was actually that secure). The thing is, inside my script that initializes the different objects, I’ve got a too long snippet for the $User object. Other objects require as little as $Browser = new Browser(); or $_ = new Translate ($DB, $User->get('Language'));. So, it feels kind of ugly to have all this code suddenly here:
/* USER. Handles user data and login/logout/register. */
$User=new User($DB, Configuration::get('SiteKey'));
if (isset($_POST['logout']))
$User->logout();
else if (isset($_POST['login']) && !$User->login($_POST['email'], $_POST['password'])) // If user tries to login
$Error->set ('Banner', 'Username or password incorrect. Please try again.');
else if (isset($_SESSION['email']) && isset($_SESSION['session']))
$User->loginSession ($_SESSION['email'], $_SESSION['session']);
else if (isset($_POST['register']))
$User->add ($_POST);
/* Language */
if (!empty ($_POST['lang']) && in_array($_POST['lang'],Configuration::get('SupportedLanguages')))
{
$User->set('language', $_POST['lang']);
$_SESSION['language'] = $_POST['lang'];
}
if (!$User->get('language'))
$User->set('language', Configuration::get('DefaultLanguage'));
I’m not sure where all this code is supposed to be, should I put this inside the User’s class __constructor() or this is it supposed to be outside as it is now?
It’s better to pass the $_POST than using it directly inside, which might affect the answer (a __constructor() with too many variables passed isn’t also really good).
I don’t think the code within the class is so relevant as to append it here, but if you want to see it I just made it publicly available in my github.
I wouldn’t put it in the constructor. Whatever script or class you have this code in looks to perform a number of responsibilities. You could consider following the single responsibility principle and separate out this code into other classes such as an authentication class, a session class and a user factory that can build the user object. A brief and by no means carefully architectured example:
Well you can always group variables into a collection object and pass that in the constructor. For example language and time settings could be grouped into a culture object.