r/PHPhelp • u/[deleted] • Jan 16 '17
My "User" class
Can I ask for a critique of this class I've written?
Bunch of functions, I'll explain:
User creates an account on the login form which just asks for email address, password, and to verify that password ($email, $password and $verify).
That all gets passed to the validateUser() function, which spits out a true or false after checking if the email address is acceptable (after sanitizing it and validating it), unique, whether the password and verification match, and if the password is over a certain number of digits long (6 for now, but i'll make that bigger).
If all of those pass, we then:
run the email through the sanitize and verify again, hash the password, create a UUID and put that all in the database with the createUser function.
I sanitize and validate the email a second time because the first function only returns true or false, nothing else.
Once that occurs, I select the UUID from the database based on the email address that was just inserted (getUserValidationKey()), and send email that to that same address (using PHPMailer).
Finally, the recipient receives that email with a link to activate.php?key=xxxxx - xxxx is the $uuid I sent them - if that UUID exists then the user becomes activated by calling the activateUserByKey() function.
Of course, I think I've done this alright. All the database interactions are done with parameters and prepared statements. The UUID is seeded with a random string from OpenSSL. And I am ASSSUMING that people won't be able to cram garbage into the email address field to turn my machine into a spammer thanks to it refusing to proceed if the email address isn't valid.
On thing I noticed is if someone puts a (space) in an email address, the validation function removes it. I think that's acceptable, probably a typo. And if it was a typo and gets sent to the wrong address, they'll just get one email by mistake.
So... Any suggestions? Particularly nervous since this is sending emails, but any other suggestions would be great.
Or.... Is it finally time to scrap standard PHP and move to a framework?
2
u/colshrapnel Jan 17 '17
You shouldn't create a new PDO connection for the every single object. This is a schoolbook error which will make you end up with hundreds database connections. Make it a constructor parameter. Id user not found, userLogin will give you an error, you have to check the query return as well, as shown here https://phpdelusions.net/pdo/password_hash
1
Jan 17 '17
OK... I took your Database.php file in whole.
Each page loads all the includes files, so I didn't need to add anything about require_once.
Then, once inside the User.php file that was posted, I removed the __constructor, and replaced the $this->db->run statements with DB::run instead... Is that what you were suggesting? And is that what I should be replicating elsewhere?
I went on to google PHP Dependency Injection, but it's pretty much beyond my understanding at this point.
Lastly, I am not replicating any errors in the userLogin. If I choose a user that doesn't exist or leave it blank, it returns the session error that user/password couldn't be found.
I had originally tried to enclose that in an if statement, figuring if it found a record it would be true otherwise false, but it seemed like it returned true because the query executed, not because it found anything, so I scrapped that and just went on to compare the POSTed password with the hash already stored and basing my true/false off the result of that.
Can you point me towards how I could "break" it or at least generate an error of some sort? Because right now it doesn't seem to do what you're saying it would...
1
u/colshrapnel Jan 17 '17
well actually it's much simpler
class user { private $db; public function __construct($pdo) { $this->db = $pdo; } } $pdo = new PDO(...); $user = new user($pdo);
make your PHP error_reporting to E_ALL and see
1
Jan 17 '17
As for the second point, I'm really pulling my hair out now. It's been set to E_ALL all along, no errors to be found.
ini_set('display_errors',1); error_reporting(E_ALL);I upgraded from PHP5 to 7 recently, and just copied the php.ini for development systems to the /etc/php/7.0/apache2 directory.
phpinfo() reports:
display_errors On display_startup_errors On error_reporting 32767 html_errors On log_errors OnStill cannot not seeing any errors on screen or in logs? Can't figure out what I'm doing wrong...
2
u/colshrapnel Jan 17 '17
the error is simple In case a user not found, there will be no $user['password'] variable and PHP will throw a notice, if configured to E_ALL
1
Jan 17 '17
Ok - so to your first point.
In the page setup file (i call it bootstrap.php), that's where I create the new PDO object? Or in the case of your wrapper, a new MyPDO object? And pass that into User that way? Trying right now...
1
Jan 17 '17
OK.
My database credentials are all defined in config.php.
bootstrap.php now contains these lines of yours:
const DBPARAMS = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false,];
$pdo = new MyPDO("mysql:host=" . DBHOST . ";dbname=" . DBNAME . ";charset=" . DBCHARSET, DBUSER, DBPASS, DBPARAMS);And when I create the User class as $user =new User($pdo);
I had to revert the DB::run's to $this-db's, but functions... Is that what your suggestion was?
I have a few other classes that I was doing my/the wrong way, so if this is proper and I just need to add the contstructor and create them using the same $pdo, that's what I'll do...
I'll end up with something like this:
$user = new User($pdo); $poll = new Poll($pdo); $admin = new Admin($pdo);1
2
u/colshrapnel Jan 17 '17
yes, in your bootstrap file create a single myPDO instance that have to be used for all the DB interactions down the code
2
u/headzoo Jan 17 '17
Have a look at dependency injection. Here's a PHP example. Like /u/colshrapnel said, you shouldn't be creating a PDO instance inside of your class. An instance of PDO should be passed to your class constructor. In a real application, other parts of the system will need a database connection too. The way you're doing it also makes your class difficult to test.
The class should be throwing exceptions on error, not setting $_SESSION values. Doing so tightly couples your class to HTTP requests, but what if you want to create a user on a backend in a cron job? Either way, you're mixing concerns.
Some of the names you chose for methods aren't very good. validateEmail() is actually filtering them. checkPasswordLength() is not checking the length of the password. It's simply returning the length of the password.
Some of the methods are just pointless. Like checkPasswordLength(), doPasswordsMatch(), and hashPassword(). You're creating abstraction that will only lead to confusion.
Everything needs documentation!
I would say your class is doing too much and mixing concerns. Is the class meant to query the database for user info? Or set session values? Or validate user info? Classes should have one specific job.
1
Jan 17 '17
I read that page and as much as I wanted to understand, it didn't register...
I've got the PDO under control now - $pdo is created in the bootstrap file, and passed into each class (each class has its own constructor).
I've been feeling like setting error messages as session variables inside the class hasn't been proper, but I was wary of using try/catch, because I didn't want to splash an ugly error message on the screen, just provide feedback to the user in a readable format (there's a a info box that only appears if $_SESSION['message'] and $_SESSION['message-type'] are set... I'm open to other better methods obviously!)
Noted about the naming of functions.
And the "pointless" functions were created because I read somewhere that it's preferable to have lots of discrete functions rather than one function that's 100 or 200 lines. I actually had all of that working within the function originally, then broke them out to sub/private functions after reading that.
You're saying it would be preferable to have a single processPassword function that checks the length, verifies that the passwords match returns false if those fail, and then either returns a hashed password if they succeed?
I thought the classes purpose was to handle every aspect of User functions. I was going to add changePassword and resetPassword functions and thought I was getting close to having this be good.
I'm really enjoying PHP at this point, but some days I fear it's a hopeless endeavor... Every step forward I make, I feel daunted about everything else I have to learn still... Thanks for putting up with me!
1
u/headzoo Jan 17 '17
I read that page and as much as I wanted to understand, it didn't register...
Yeah, don't worry about that. With programming, you do certain things because people tell you it's the "right way" and eventually you come to understanding why it's done that way. For instance DI (dependency injection) is crucial to unit testing, but you're not unit testing yet, but you should build good habits even before you understand why.
I've been feeling like setting error messages as session variables inside the class hasn't been proper, but I was wary of using try/catch, because I didn't want to splash an ugly error message on the screen
You could be using code like this:
try { $u = new User($pdo); $u->validateUser("foo", "bar", "bar"); } catch (\Exception $e) { $_SESSION['message'] = $e->getMessage(); $_SESSION['message-type'] = 'error'; }It accomplishes the same thing without tying the user class to sessions.
And the "pointless" functions were created because I read somewhere that it's preferable to have lots of discrete functions rather than one function that's 100 or 200 lines.
That is true, but you're creating discrete functions which wrap discrete functions. The
password_hash()andstrlen()functions are already very discrete. There's no need to wrap them. It just adds confusion when other developers are trying to understand what your code does. Rule #1 with programming: don't try to be too clever!I thought the classes purpose was to handle every aspect of User functions.
It could be, but your class could still be broken up into smaller classes with single responsibilities. Single responsibility principle.
$pdo = new PDO(...); $validator = new EmailValidator(); $uuid_gen = new UUIDGenerator(); $user = new User($pdo, $validator, $uuid_gen);You're going to find that you will have the need to query the database, validate email addresses, and create UUIDs outside of your
Userclass. So it makes sense to create separate classes/functions for that functionality.1
Jan 17 '17
OK...
I think at this exact moment, I'm going to ignore the try/catch and concentrate on class construction...
I dropped the UUID generation function I was using, and created a new UUID class from the example on PHP.net.
Now, when I create the new user class, i'm going
$pdo = new PDO(...); $uuid = new UUID(); $user = new User($pdo, $uuid);
and in the constructor, I've added $this->uuid = $uuid and modified the other reference based on that.
I created a user and all seems to work.
My question/concern is this:
I had thought if i created a class for this project, I would be able to basically use this class in a completely unrelated project. But now, I can't just copy this class to a completely unrelated project without also copying the UUID.php file as well.
Probably not something I should worry about yet, but if I continue down this path I feel like I'm going to have 25 inter-related class files that all relate to each other in different ways. I assume there's a solution to this somewhere down the road? :)
2
u/headzoo Jan 17 '17
Well... now we're getting into some more complicated concepts. :)
You're right... you may want to use those classes in other projects, and you're right.. it would be tedious to copy the UUID.php to all of your projects. It would be even more tedious when you need to make changes to the
UUIDclass to all of the projects using it. So far, you're asking the right questions. The answer to this question is to create a package.A package is just a reusable component/library that can be shared among projects. Each programming language has something called a package manager which helps you to find, download, and update the packages your app needs. PHP's package manager is Composer. Composer is not built into PHP. It's a simple CLI (command line) utility that works along side of PHP.
If you poke around some PHP projects on github, you will see that nearly every single one of them contains this magical file named
composer.json. For instance guzzle/guzzle. That file defines which packages the application depends on. The composer CLI utility reads the file, downloads those packages, and installs them locally for the app to use. Information about every available package is available on https://packagist.org.This all gets a little complicated at first, but trust me, once the concept "clicks" it's actually very simple.
Before getting into creating a package, let's look at using one. As it turns out, some enterprising PHP developers have already created UUID libraries. For instance https://packagist.org/packages/ramsey/uuid. So instead of writing your own, let's use the one that already exists. Start by installing Composer. Follow the directions from the composer site.
At the root of your application, where the
bootstrap.phpfile exists, create a file namedcomposer.json, and add the following.{ "name": "lucasjkr/multi-vote-polling-application", "description": "A simple app to pole your site visitors.", "authors": [ "lucasjkr" ], "require": { "ramsey/uuid": "3.5.2" } }The
composer.jsondefines some information about your application, and the packages/libraries it depends on. In this case your app depends on "ramsey/uuid" version 3.5.2.From the command line in your app's root directory type
composer install. Assuming you installed Composer correctly, you will see a bunch of stuff output on your screen while Composer reads the json file and downloads the required packages. Once finished a new directory will have been created by Composer in the app's root directory namedvendor. Take a look inside it. It contains the packages/libraries your app depends on.We're almost finished! In order to use those packages/libraries, you need to modify your
bootstrap.php. Near the top of the script add this code:include("vendor/autoload.php");Now you can use the "ramsey/uuid" package.
<?php use Ramsey\Uuid\Uuid; ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); session_start(); include("vendor/autoload.php"); include('config.php'); /** other stuff here **/ $uuid = Uuid::uuid1(); $user = new User($pdo, $uuid);Any time you change the
composer.jsonfile, you should run the commandcomposer update. Composer will update the contents of thevendordirectory to reflect your changes.Also, you should not add the
vendordirectory to your git repo. So add "vendor/" to your.gitignorefile. Composer also creates a file namedcomposer.lockin the root of your app. You may want to add that to your.gitignoreas well.I'll let that sink in for a bit before going any further.
1
Jan 17 '17
OK... I've got Ramsey's UUID coming in through composer. Deleted the UUID class I'd just made, and again, all is working fine.
I looked up PHP Mailer and since that's on Packagist, too, I'm bringing that in through composer, rather than just using the two class files I downloaded from Github. I'll have to look at the documentation to figure out how to initialize PHPMailer now that its in the vendor directory.
I can see eventually I'll be able to inject PHPMailer into the User class as well, so I can have account verification and password reset emails handled directly in the User class. Not there yet, first I'm going to try to use this new version of PHPMailer...
And then the whole container concept looks like it'll make life a LOT easier with all of these components.
Where should I put these functions that create the containers... In their own containers.php file, or as functions at the end of the class file, so I can call them to create the new class?
I'm thinking the second one where the single file is like:
<?php class name { function type() { .... } } function nameService() { .... }Or, I could add each container to the bootstrap.php file.
Many thanks to you!
1
u/headzoo Jan 17 '17
You could add the factory functions to the class files, but that approach is usually frowned upon. Though I do see that approached used sometimes.
Since you've got the swing of using Composer already (that was fast!) you may want to have a look at Pimple. Try this example in a file named
container.php.<?php use Pimple\Container; $container = new Container(); $container["config"] = function() { include("config.php"); return $config; } $container["pdo"] = function() { $config = $container["config"]; $pdo = new MyPDO( "mysql:host=" . $config["host"] . ";dbname=" . $config["name"] . ";charset=" . $config["charset"], $config["user"], $config["pass"], $config["params"] ); return $pdo; } $container["uuid"] = function() { return Ramsey\Uuid\Uuid::uuid1(); } $container["user"] = function() { return new User($container["pdo"], $container["uuid"]); } return $container;Then from the
bootstrap.phpfile you can use the container like this:$container = include("container.php"); $pdo = $container["pdo"]; $user = $container["user"];The upside of using Pimple (or any good container) is that it caches objects (singleton pattern) during the first request for the object.
$pdo1 = $container["pdo"]; $pdo2 = $container["pdo"]; var_dump($pdo1 === $pdo2); // Outputs "true"The function which creates the PDO instance only gets called once. When you used
$pdo1 = $container["pdo"]. After that, Pimple "caches" the object, and will return that same cached object each time you call$pdo = $container["pdo"]. That way you don't need to worry about accidentally establishing multiple database connections.You can recreate that "singleton" strategy if you decide to write simple service functions.
function pdoService() { static $pdo = null; if ($pdo === null) { $pdo = new MyPDO(...); } return $pdo; }Now when you call
pdoService(), the PDO object only gets initiated once. Each successive call topdoService()returns the same object.Even if you don't use Pimple, it may give you some ideas on structuring your code. The short and skinny is you should have a separate
container.phpfile where your services are defined.1
Jan 17 '17
A friend I had been helping with Behat stuff with a year ago had gotten me to install composer at the time... So whatever is on my machine is probably outdated, but it works! Your example composer.json file had issues - it kept giving JSON errors, but I found a project on Github and copied its structure and renamed what needed to be renamed.
But besides that, I didn't really get the "swing" of it, I just followed instructions! And it turned out I needed to make no changes at all to use the PHPMailer, since I was already loading it - all that changed was the disk location of the files (from my include/ to the new vendor/phpmailer directory)
Pimple looks interesting. I'll have to re-read your post more thoroughly and read its documentation... I just need to rotated to a quieter coffee shop first, which I'm doing now
1
u/headzoo Jan 17 '17
Don't worry too much about understanding it all today. Just giving you something to chew on over the next couple weeks/months.
Incidentally, you can run the command
composer self-updateto automatically update your version of Composer.2
Jan 17 '17
Well, I've been enjoying wrapping my head around things today! I really need to find a local group that does this sort of thing, I think. But /r/PHPHelp has been a godsend so far, I think...
And yes, got my composer updated to 1.3.1, looks like I was at version 1.2.0 previously, so a bit outdated. Thanks!
→ More replies (0)1
u/colshrapnel Jan 17 '17
What a relief to see such a sane response. The guy have no idea what he is talking about. Although exceptions could be used here, but absolutely not the way he is offering.
0
u/colshrapnel Jan 17 '17 edited Jan 17 '17
That's just a nonsense. catching \Exception will make your code a fucking mess.
1
u/headzoo Jan 17 '17
Fuck off, asshole. I've been doing this for 12 years. My sites get 20 million page views a day. I kind of know what I'm doing. I was giving the "noob" an easy to follow example.
Go take a chill pill.
1
u/colshrapnel Jan 17 '17
Go boast somewhere else. If you can't tell an error exception from a validation exception you shouldn't be allowed to code even an elementary school homepage.
1
u/headzoo Jan 17 '17
Dipshit, the "noob" doesn't even know what exceptions are. By all means though, go down that rabbit hole with him in order to show a simple example.
0
u/colshrapnel Jan 17 '17
It's better not to know at all than learn the wrong way from you. Just stay away from exceptions if you don't know how to use them yourself.
1
Jan 17 '17
For what its worth, this is what I'm working on. I'm sure you'll call it spaghetti code, but I'm learning and enjoying!:
https://github.com/lucasjkr/multi-vote-polling-application
Testing site:
http://autonomous.lucaskrupinski.com/
Those session messages from the User class get output below the distiller logo.
(the array at the bottom of the page is just the session variables just so i can see what's in there)
2
u/headzoo Jan 17 '17
Looks good so far!
One thing I wanted to mention.. Take another look at this code example:
$pdo = new PDO(...); $validator = new EmailValidator(); $uuid_gen = new UUIDGenerator(); $user = new User($pdo, $validator, $uuid_gen);It would be very tedious writing those 4 lines of code every single time you needed a
Userinstance. That's where the dependency injection container comes into play. I'll let you google around a bit for more info, but for now you can simply make a function which returns aUserinstance.function userService() { $pdo = new PDO(...); $validator = new EmailValidator(); $uuid_gen = new UUIDGenerator(); $user = new User($pdo, $validator, $uuid_gen); return $user; }Now you can use
$user = userService()anytime you need an instance.A more complete "homebrewed" dependency injection container might look something like this:
/** * A simple dependency injection container */ class Container { /** * @var array */ private $config = []; /** * Constructor * * @param array $config The system configuration */ public function __construct(array $config) { $this->config = $config; } /** * @return array */ public function configService() { return $this->config; } /** * @return MyPDO */ public function pdoService() { $config = $this->configService(); $pdo = new MyPDO( "mysql:host=" . $config["host"] . ";dbname=" . $config["name"] . ";charset=" . $config["charset"], $config["user"], $config["pass"], $config["params"] ); return $pdo; } /** * @return EmailValidator */ public function emailValidatorService() { return new EmailValidator($this->configService()); } /** * @return UUIDGenerator */ public function uuidGeneratorService() { return new UUIDGenerator($this->configService()); } /** * @return User */ public function userService() { $pdo = $this->pdoService(); $validator = $this->emailValidatorService(); $uuid_gen = $this->uuidGeneratorService(); $user = new User($pdo, $validator, $uuid_gen); return $user; } }And inside your bootstrap.php:
include('config.php'); $container = new Container($config);Now when your code needs a pdo instance, you use
$pdo = $container->pdoService(). When you need a user instance, you use$user = $container->userService(). You would also use$container->configService()instead of passing the$configarray around everywhere.Dependency injection is just a fancy way of saying, "Pass the objects your class needs instead of creating them inside the class." That's it! A really fancy name for a very simple concept. In this case the word "dependency" refers to the objects your class depends on to function. Your
Userclass depends on thePDOclass, and you inject an instance of pdo into the user class through its constructor.A dependency injection container is just a class/framework that "wires up" the dependencies for you. So that you can create instances of classes by calling a single function, e.g.
$container->userService(), instead of creating them manually.Good luck!
1
u/emelpy Jan 17 '17
To speak to your last point, it's probably best to scrap vanilla PHP and move to a framework. If for no other reason than it will help you gain exposure to writing modular, more maintainable code. The biggest problem with this implementation is that your entity has way to much knowledge/responsibility w.r.t the system as a whole. Ideally an entity has no information about how it is persisted (e.g. written to a MySQL database). It only focuses what it is directly responsible for: the fields that exist on the entity, getting and setting these fields, and any sort of domain logic like validation, etc.
Similarly, the actual authentication process is probable outside of the scope of what a user entity should be responsible for. You'd do better to write an Auth class that handles this logic.
The benefits of using a framework is that most modern ones force you too follow these principles right from the get go. Most have an authentication layer built in, some sort of database abstraction layer, a session handler class, etc. Most importantly, in my opinion, they will also provide some form of dependency injection so you can be explicit about how all of these classes work together.
Following SOLID design principles can be quite difficult in practice. That's why leveraging the work of numerous highly skilled devs in employing an open source MVC can give you the benefits of high quality, modular code while you focus on solving problems specific to your domain. In the process, you'll get exposure to what this quality code should look like and start to build a deeper understanding of when and why these principles are applied.
As far as what framework to go with, I leave that to the reader. They all have their pros and cons but for someone just starting out it's pretty much irrelevant.
1
Jan 17 '17
Thank you for all of that! I have a laravel book that I keep meaning to dig into, but instead keep embarking on these small projects under the assumed I should be learning more about php before moving forward. But everything you said makes sense. I just wonder if there are any books about good programming practices in general that you would recommend I check out? Or should I work my way through that first ( it's the just released o'rielly book if that makes a difference)
1
Jan 16 '17
might want to consider checking if a session exists in the constructor before setting values
1
Jan 16 '17
I start sessions on all the regular pages, set the user I'D to 0 if they're not logged in, and only show the registration and logging pages if they're not logged in.
Is that ok? Or should I be initiating the session within the class rather than just setting session messages?
2
u/mik3w Jan 16 '17
I can't see what the "verify" variable is exactly, with the function validateUser, but I can't see:
https://secure.php.net/manual/en/function.password-verify.php
even though you use
If it's actually working properly I'm certain that this wouldn't work: