PHP: Building A Simple Password Encrypter

If you use design patterns in your daily PHP programming work and want to learn how to implement another one, then hopefully this four-part series of articles has been instructive. It demonstrated how to create easily immutable value objects by means of the Value Object pattern. In this last part, you’ll learn how to use this design pattern for encrypting passwords.

Needless to say, if you’ve already read all of the articles previous to this one, you probably have a solid background in how to apply the pattern in distinct use cases. Over the course of those tutorials I demonstrated, with some practical examples, how to create different types of immutable objects. These ranged from simple URL objects to HTML widgets capable of rendering simple div elements on screen.

This doesn’t imply, however, that the implementation of the Value Object pattern must be restricted to generating the kind of objects just mentioned. The schema can be easily extended to other objects as well, depending on the domain layer being modeled. With that premise in mind, in this final installment of the series I’m going to create yet another easy-to-follow example. It will show how build immutable objects whose functionality will be focused on encrypting passwords (or any other string value) via a set of discrete methods.

With the goal of this article already set, it’s time to tackle the last chapter of this series on implementing the Value Object pattern in PHP. Let’s jump in!

Getting started: building a basic class for encrypting passwords

As I stated in the introduction, I plan to implement the Value Object pattern in the construction of a basic password encrypting class. Similar to the examples developed previously, it will be immutable as well. Since the term “encrypt” describes a somewhat generic action, the class will be an implementer of an interface called “EncrypterInterface,” which will define the structure of generic encrypting objects. The definition of this interface looks like this:

(EncrypterInterface.php)

<?php

interface EncrypterInterface
{
    public function encrypt($value); 
}

As you can see, the above interface is very simple, as it only declares a single method called “encrypt().” With that base structure already set on top of the hierarchy, the next step is to define the implementer of the interface, which will be a class tasked with constructing immutable password encrypting objects.

Having said that, the definition of this class (at least at its initial stage) will be as follows:  

(PasswordEncrypter.php)

<?php

final class PasswordEncrypter implements EncrypterInterface
{
    private $_password;
   
    public function __construct($password)
    {
        if (!is_string($password) || empty($password)) {
            throw new PasswordEncrypterException(‘The specified password is invalid.’);
        }
       
        $this->_password = $this->encrypt($password);
    }
   
    // get the encrypted password
    public function getPassword()
    {
        return $this->_password;
    }
   
    // encrypt the password
    public function encrypt($value)
    {
        return sha1($value . (string) microtime(true));
    }
}

As with other immutable classes that you saw in earlier parts of this series, the one above acts like a raw data container. It stores the password passed through the constructor, after being encrypted via a “sha1” hash. Naturally, it’s possible to apply more complex approaches to encrypting values, but for the sake of clarity I’m going to keep the class simple.

So far, half of the goal has been accomplished. The “PasswordEncrypter” class is effectively capable of generating immutable value objects. But, is that all of the behavior that it will be given? To be frank, it’d be helpful to extend its current functionality a bit further; right now, it does nothing particularly interesting.

To satisfy this requirement, and make things a little more exciting, in the next section I’m going to add an additional method to the class. This method will be responsible for generating new encrypted passwords, while preserving the class’s immutability.

This sounds pretty good, right? However, to learn how this method will be implemented, you’ll have to read the following segment. Fear not; it’s only one click away.

{mospagebreak title=Regenerating passwords via a simple method}

While in its current state the earlier “PasswordEncrypter” class admittedly does a good job of encrypting passwords, it still lacks more complex behavior. To address this issue and extend its actual functionality, I’m going to add to the class a brand new method. Called “regenerate(),” it will use composition to create new encrypting objects. The implementation of this method is shown below, so pay close attention to it:

// generate a new encrypted password (returns a new PasswordEncrypter object)
public function regenerate(PasswordEncrypter $passwordEncrypter)
{
    $password = $this->getPassword() . $passwordEncrypter->getPassword();
    return new PasswordEncrypter($password);
}

Definitely, at this point you’ll agree with me that the underlying logic of the “regenerate()” method is very easy to follow. It simply injects a new password encrypting object and then generates a new one, based on a combination of existing passwords.

This illustrates, once again, a typical characteristic of any immutable value object: any algorithm or additional form of processing applied to one or more fields will result in the generation of a new value object. The principle is clear and straightforward, so make sure to remember it when developing your own immutable object, and everything will work fine.

So far, so good. Now that the functionality of the “PasswordEncrypter” class has been expanded to a certain extent, the last thing we need to do is show its full source code, after adding the “regenerate()” method. Here it is:

(PasswordEncrypter.php)

<?php

final class PasswordEncrypter implements EncrypterInterface
{
    private $_password;
   
    public function __construct($password)
    {
        if (!is_string($password) || empty($password)) {
            throw new PasswordEncrypterException(‘The specified password is invalid.’);
        }
       
        $this->_password = $this->encrypt($password);
    }
   
    // get the encrypted password
    public function getPassword()
    {
        return $this->_password;
    }
   
    // encrypt the password
    public function encrypt($value)
    {
        return sha1($value . (string) microtime(true));
    }
   
    // generate a new encrypted password (returns a new PasswordEncrypter object)
    public function regenerate(PasswordEncrypter $passwordEncrypter)
    {
        $password = $this->getPassword() . $passwordEncrypter->getPassword();
        return new PasswordEncrypter($password);
    }     
}

Done. At this stage, the “PasswordEncrypter” class is not only capable of spawning encrypting value objects in a snap, but thanks to the “regenerate()” method, it can create new value objects transparently, behind the scenes. Not too bad, huh?

But hold on a second! The class is apparently functional, at least from a bird’s eye view, but it’d be desirable to create an example that shows how to work with it. Therefore, in the last part of this tutorial I’m going to set up such an example. So go ahead and read the section below. 

The “PasswordEncrypter” class in action

If you want to see how the previous “PasswordEncrypter” class works when used in a concrete situation, below I included a basic example that first creates two encrypting value objects, and then a third one, via the class’s “regenerate()” method. Here’s the example:

// example of immutable value objects using the PasswordEncrypter class

require_once ‘EncrypterInterface.php';
require_once ‘PasswordEncrypter.php';

// create two password encrypter objects
$encrypter1 = new PasswordEncrypter(‘mysecretpass’);
$encrypter2 = new PasswordEncrypter(‘myothersecretpass’);

// generate a new encrypted password (returns a new PasswordEncrypter object)
$encrypter3 = $encrypter1->regenerate($encrypter2);
echo $encrypter3->getPassword();

/*
displays the following

de4af02aecc486a3405c4cfd259f666ed082de6b
*/

While the above code snippet isn’t suitable for use in production environments, it is useful for demonstrating how to implement the Value Object pattern in different use cases. In the previous example, the “regenerate()” method deserves a special mention. It’s particularly helpful for spawning a new value object, simply by internally combining the passwords of the other two objects created at the beginning of the script.

Logically, it’s possible to model different types of value objects, other than the ones shown in this article series. Thus, if you feel especially interested in tackling this task on your own, then go for it. It will be a en effective way to expand your existing background in using design patterns in the field of PHP programming. 

Final thoughts

Nothing lasts forever, and this article series certainly isn’t the exception. Nonetheless, the journey has been instructive, as you learned how to create immutable objects in PHP through some simple and customizable examples.

Since PHP is just starting to adopt more complex methodologies for developing web applications, creating immutable value objects with it can seem to be more of a hassle than truly useful. Don’t be fooled by this first impression, as value objects are an important pillar of Domain-Driven design, and in general of object-oriented programming. So, my recommendation is that you start looking at them, especially if you’re planning to create your next web programs using a DDD methodology.

See you in the next PHP web development tutorial!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan