Handling Object Dependency
<p>Consider the following class</p>

<pre><code>class User
{
    protected $password;

    public function setPassword($password)
    {
        $this-&gt;password = $password;
        return $this;
    }

    public function getPassword()
    {
        return $this-&gt;password;
    }
}
</code></pre>

<p>I want to apply bcrypt on password using <code>Zend\Crypt\Password\Bcrypt</code> in user object, since this creates a dependency i want to know how to correctly deal with this, i can think about several approaches to make this work, let me elaborate</p>

<p><strong>Approach 1</strong> : Here we instantiate the class inside the method and apply required changes.</p>

<pre><code>class User
{
    protected $password;

    public function setPassword($password)
    {
        $bcrypt = new Bcrypt();
        $this-&gt;password = $bcrypt-&gt;create($password);
        return $this;
    }

    public function getPassword()
    {
        return $this-&gt;password;
    }

    public function verifyPassword($password)
    {
        $bcrypt = new Bcrypt();
        return $bcrypt-&gt;verify($password, $this-&gt;getPassword());
    }
}
</code></pre>

<p>Towards my understanding this is not recommended approach since i see two problems here</p>

<ol>
<li>Bcrypt() is instantiated twice</li>
<li>This makes User object tightly coupled with Bcrypt</li>
</ol>

<p>I can solve problem-1 by instantiating Bcrypt() once in class constructor and use it whenever required, however this does not solve problem-2</p>

<p><strong>Approach 2 :</strong> Move Bcrypt object out of user class and inject it while setting the password</p>

<pre><code>class User
{
    protected $password;

    public function setPassword($password)
    {
        $this-&gt;password = $password;    
        return $this;
    }

    public function getPassword()
    {
        return $this-&gt;password;
    }
}

// Init Bcrypt
$bcrypt = new Bcrypt;

// Instantiate user object and create a password
$user = new User;
$user-&gt;setPassword($bcrypt-&gt;create($password));

// Verify user password
if ($bcrypt-&gt;verify($password, $user-&gt;getPassword())) {
    // Password is verified
}
</code></pre>

<p>What is the best way to about it ?</p>

<p>Thanks.</p>