<?php
namespace Backend\Models;
use Common\Base\Model;
class News extends Model {
protected $table = 'news';
protected $key;
public function allNews() {
while(!$rows = parent::findAll()){
throw new \Exception('not find news');
}
return $rows;
}
public function insertNews(Array $array) {
$params = [
"id" => $array['news_id'],
"header" => $array['news_header'],
"text" => $array['news_text'],
"url" => $array['news_url']
];
$sql = "UPDATE {$this->table} SET `header` = :header, `text` = :text, `url` = :url WHERE `id` = :id";
if( !parent::save( $params, $sql ) ) {
throw new \Exception('Ошибка сохранения новости');
}
}
public function getSingle($key, $param = []) {
$this->key = $key;
if( !$rows = parent::findBy($param) ){
return false;
}
return $rows;
}
}
<?php
namespace Common\Base;
use Common\Connection;
abstract class Model {
/**
* prefix for tables
*/
const PREFIX = "";
/**
* @var
*/
protected $table;
/**
* @var
*/
protected $key;
/**
* @return mixed
*/
public function findAll() {
return $this->fetch("SELECT * FROM " . self::PREFIX . $this->table . " ");
}
/**
* @param array $args
* @return array|string
*/
public function findBy(Array $args) {
$stmt = Connection::con()->prepare("SELECT * FROM " . self::PREFIX . $this->table . " where {$this->key} = ?");
$data = "";
if ( $stmt->execute($args) ) {
while ($row = $stmt->fetch()) {
$data[] = $row;
}
}
return $data;
}
/**
* @param $query
* @return mixed
*/
protected function fetch($query) {
$stmt = Connection::con()->query($query);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$data = "";
while ($row = $stmt->fetch()) {
$data[] = $row;
}
return $data;
}
protected function save(Array $array, $sql) {
$sth = Connection::con()->prepare($sql);
return $sth->execute($array);
}
}