Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Created January 18, 2011 13:38
Show Gist options
  • Save Mikulas/784438 to your computer and use it in GitHub Desktop.
Save Mikulas/784438 to your computer and use it in GitHub Desktop.
<?php
namespace Model;
class Post extends BaseModel
{
/** @var int */
private $id;
/** @var string */
private $label;
/** @var string */
private $text;
/** @var integer */
private $views = 0;
/** @var boolean */
private $published = FALSE;
/**
* @param int $id
* @throws ModelException when id does not exist
*/
public function __construct($id = NULL)
{
parent::__construct();
if ($id !== NULL) {
$this->id = $id;
$res = $this->db->fetch('SELECT label, text, views, published FROM post WHERE id=?', $this->getId());
if ($res === FALSE) {
throw new ModelException("Post with id $id does not exist");
}
foreach ($res as $property => $value) {
$this->$property = $value;
}
}
}
/**
* @return Post provides fluent interface
*/
public function save()
{
if ($this->id === NULL) {
$this->db->exec('INSERT INTO post', array(
'label' => $this->getLabel(),
'text' => $this->getText(),
'views' => $this->getViews(),
'published' => $this->getPublished(),
));
$this->id = (int) $this->db->lastInsertId();
} else {
$this->db->exec('UPDATE post SET ? WHERE id=?', array(
'label' => $this->getLabel(),
'text' => $this->getText(),
'views' => $this->getViews(),
'published' => $this->getPublished(),
), $this->getId());
}
return $this;
}
public function delete()
{
return $this->db->exec('DELETE FROM post WHERE id=?', $this->getId());
}
/**
* @return int id
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getLabel()
{
return (string) $this->label;
}
/**
* @param string $value
* @return Post provides fluent interface
*/
public function setLabel($value)
{
$this->label = (string) $value;
return $this;
}
/**
* @return string
*/
public function getText()
{
return (string) $this->text;
}
/**
* @param string $value
* @return Post provides fluent interface
*/
public function setText($value)
{
$this->text = (string) $value;
return $this;
}
/**
* @return integer
*/
public function getViews()
{
return (int) $this->views;
}
/**
* @param integer $value
* @return Post provides fluent interface
*/
public function setViews($value)
{
$this->views = (int) $value;
return $this;
}
/**
* @return boolean
*/
public function getPublished()
{
return (bool) $this->published;
}
/**
* @param boolean $value
* @return Post provides fluent interface
*/
public function setPublished($value)
{
$this->published = (bool) $value;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment