HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Critique request: PHP cookie library

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
critiquephprequestcookielibrary

Problem

I've written a fairly small library that abstracts cookie functionality in a way that mimics working with a database model. The repository is on bitbucket and the code is small enough to embed here:

```
class SimpleCookie {

/**
* Cookie value char limit
* @var int
*/
const valueLimit = 2000;

/**
* Cookie data
* @var array
*/
protected $cookieData = array();

/**
* Cookie name
* @var string
*/
protected $cookieName = null;

/**
* If cookie exists, it get's loaded on construct
*
* @param string $cookieName
*/
public function __construct($cookieName) {
$this->load($cookieName);
}

/**
* @param string $key
* @return mixed
*/
public function __get($key) {
return
isset($this->cookieData[$key])
? $this->cookieData[$key]
: null;
}

/**
* @param string $key
* @param mixed $value
*/
public function __set($key, $value) {
$this->cookieData[$key] = $value;
}

/**
* @param string $key
* @return bool
*/
public function __isset($key) {
return isset($this->cookieData[$key]);
}

/**
* @param string $key
*/
public function __unset($key) {
if(isset($this->cookieData[$key])) {
unset($this->cookieData[$key]);
}
}

/**
* Load a cookie
*
* @param string $cookieName
* @return SimpleCookie|false
*/
public function load($cookieName) {
$this->setName($cookieName);

if(!$data = $this->getCookie($this->cookieName)) {
return false;
}

if(is_array($data)) {
$data = implode("", $data);
}

return $this->setData( $this->getCookieArray( $data ) );
}

/**
* Save a cookie
*
* @param int $expires
* @param string $path
* @param string $domain
* @param bool $secure

Solution

Code quality

Well, I did not try your code, but at a first glance it seems to be very robust code. But for further development I would recomend you to set up a test case for your class. See http://www.phpunit.de.

Code clarity

The only part where I got stuck a bit was the save method, but after a second read I got the point. In my opinion any programmer with sufficient oo skills can get your code after one or two reads.

Comments sufficiency

Sometimes you comment, when there is no need for it. Consider the save method: through the methods name it should be clear, that a cookie gets saved. So no need for this comment. Same goes for the constructor, the load, setCookie, getCookie, setData and setName methods. As your code is very readable, I don't see any need for this degree of commenting. I would recomend you just to use the phpdoc comments.

Context

StackExchange Code Review Q#2715, answer score: 4

Revisions (0)

No revisions yet.