Converting Static methods to non-static

hmmm i am thinking i do not know what I am taking about. lol
Been trying to convert some static methods to not be static…

Before

    protected static function forgetLogin()
    {
        $cookie = $_COOKIE['remember_me'] ?? false;

        if ($cookie) {

            $remembered_login = RememberedLogin::findByToken($cookie);

            if ($remembered_login) {
                $remembered_login->delete();
            }

            setcookie('remember_me', '', time() - 3600);  // set to expire in the past
        }
    }

After (DOES NOT LOOK AS PRETTY)

    protected function forgetLogin()
    {
        $cookie = $_COOKIE['remember_me'] ?? false;

        if ($cookie) {

            $remLoginObj    = new RememberedLogin();
            $remLoginObjTwo = $remLoginObj->findByToken($cookie); // uses FETCH_CLASS

            if ($remLoginObjTwo) {
                $remLoginObjTwo->delete();
            }

            setcookie('remember_me', '', time() - 3600);  // set to expire in the past
        }
    }

You have now tightly coupled the class. Pass what it needs with Dependency Injection.

Also, I’d recommend not to call setcookie directly, but abstract away from it. That would make it a lot easier to test.

Not sure how to use DI in this scenario.
All i can think of is to pass the cookie to the construct , call findByToken in construct which sets property

I’d do it something like this:

// not sure about this class name, feel free to use your own
// I just had to put _something_ there :D
class Authentication
{
    const COOKIE_NAME = 'remember_me';

    /**
     * @var RememberedLogin
     */
    private $rememberedLoginService;

    /**
     * @var CookieJar
     */
    private $cookieJar;

    public function __construct(RememberedLoginService $rememberedLoginService, CookieJar $cookieJar)
    {
        $this->rememberedLoginService = $rememberedLoginService;
        $this->cookieJar = $cookieJar;
    }

    protected function forgetLogin()
    {
        $cookie = $this->cookieJar->findCookie(self::COOKIE_NAME);

        if (null === $cookie) {
            return;
        }

        $rememberedLogin = $this->rememberedLoginService->findByToken();

        if (null === $rememberedLogin) {
            return;
        }

        $this->rememberedLoginService->delete($rememberedLogin);
        $this->cookieJar->remove(self::COOKIE_NAME);
    }
}

Bonus points if RememberedLoginService and CookieJar are interfaces so you can mock them in tests.

1 Like