-2

I am working on one project which redirects user to custom page after login, registration etc. FYI, the custom page can be configured as per customer from admin settings.

I am trying to follow some design-pattern guidelines to achieve this. So far I have designed my classes as below

File: RedirectInterface.php

interface RedirectInterface
{
    public function getUrl($customerId = null);
}

File: LoginRedirect.php

class LoginRedirect implements RedirectInterface
{
    public function getUrl($customerId = null)
    {
        // do some business logic here to get url
        $url = '/account/some-customer';
        return $url;
    }
}

File: RegisterRedirect.php

class RegisterRedirect implements RedirectInterface
{
    public function getUrl($customerId = null)
    {
        // do some business logic here to get url
        $url = '/welcome/some-customer';
        return $url;
    }
}

File: RedirectFactory - Creational design pattern (static factory)

class RedirectFactory
{
    public static function build($type, $customerId)
    {
        if ($type == 'login') {
            return new LoginRedirect($customerId);
        } else if ($type == 'register') {
            return new RegisterRedirect($customerId);
        }
        throw new InvalidArgumentException ('Invalid redirect type.');
    }
}

Usage:

// 1. Usage: Somewhere in customer registration code
$redirectUrl = RedirectFactory::build('register', 102)->getUrl();
header('Location: ' . $redirectUrl);

// 2. Usage: Somewhere in customer login code
$redirectUrl = RedirectFactory::build('login', 102)->getUrl();
header('Location: ' . $redirectUrl);

So my question here is:

  • What is the appropriate design pattern used in this case? like Adapter, Static Factory etc.
  • How would you refactor this sample with more clincial finish?

Thanks

1 Answers1

1

What is the appropriate design pattern used in this case?

If you mean which design pattern you picked, the answer is, this is the "strategy pattern" (with different "redirect strategies"). If it is appropriate for your case in your context, only you can tell us.

How would you refactor this sample with more clincial finish?

Why should one refactor this? The code snippet looks pretty SOLID to me, since it is "strategy pattern by the book". However, I see only your snippet, not the whole program, and I do not now which kind of evolvability you really need. Thus if this solution it is a good choice in your context, only you can tell.

For example, the current form puts the logic for finding the redirect URL, or the adding of new redirect URLs into the hands of the developer. If that is what is required, then it is ok. If not and you have the requirement to let someone else change that logic by configuration, then you probably need to refactor (or start directly with a different solution). But do not refactor just for the sake of refactoring, otherwise you end up with something like FizzBuzz Enterprise.

Doc Brown
  • 218,378