I built a class which have only static methods. This class is basically a URL builder and contains 2 public static methods. Those methods calls private methods in the same class.
My question is:
Could this class be re-written to apply a design pattern? In my mind it is close to facade or decorator! Is my approach correct?
class UrlBuilder{
/**
* @param Model $model
* @return string
*/
private static function jsonFyModelAttribute(Model $model){
return json_encode($model->attributes);
}
private static function objectFy(array $json){
return json_decode($json['payload']);
}
/**
* @param $str
* @return string
*/
private static function buildFormUrl($str){
$slug = self::encodeUrl($str);
return $url = Yii::$app->params['formsUrl'].'pay?pay=' . $slug;
}
/**
* @param Model $model
* @return string
*/
public static function sign(Model $model){
$jws = new SimpleJWS([ 'alg' => 'RS256']);
$payLoad = self::jsonFyModelAttribute($model);
$jws->setPayload([
'payload' => $payLoad
]);
$privateKey = openssl_pkey_get_private("file:///var/pems/mykey.pem");
$jws->sign($privateKey);
return self::buildFormUrl($jws->getTokenString());
}
/**
* @param $str
* @return array
*/
public static function unSign($str){
$data = self::decodeUrl($str);
$jws= SimpleJWS::load($data);
$publicKey = openssl_pkey_get_public("file:///var/pems/pubkey.pem");
if ($jws->isValid($publicKey, 'RS256')) {
return self::objectFy($jws->getPayload());
}
}
/**
* @param $str
* @return string
*/
private static function encodeUrl($str){
return urlencode($str);
}
/**
* @param $str
* @return string
*/
private static function decodeUrl($str){
return urldecode($str);
}
}
The question is, why do you want to use a Design Pattern? Design Patterns are not the solutions to everything and your code has not to contain as much as design patterns as possible. By the way: design patterns never concern a single class. It is always an interaction and communication between different classes and how to handle it.
To your example, my advice is to follow the KISS principle. And pattern can come much later, when you really need them (and it is really hard, even for experienced programmers, to identify this situation)
Lets start from definitions.
Facade - is an object that provides a simplified interface to a larger body of code, such as a class library.
Decorator - is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects.
So, your case it is not facade nor decorator. You have service which provides some helpful stuff. I think it is just helper, and you don't have to apply some design pattern to it just for design patterns...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With