justsomedev justsomedev - 4 years ago 64
PHP Question

Class contains only static function, which design pattern apply?

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);
}

}

Answer Source

The question is, why do you want to use a Design Pattern? Design Pattern are not the solutions to everything and your code has 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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download