I am using following classes/interface to redirect user (after login, register, logout etc.)
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);
If you were given a chance to refactor this code. How would you have re-developed it?