<?php
namespace %Project name%\Models;
use Mezon\Functional\Fetcher;
use Mezon\PdoCrud\ConnectionTrait;
class %Table name%Model
{
use ConnectionTrait;
/**
* Loaded data
*
* @var object
*/
private $data = null;
/**
* Constructor
*
* @param object $data
* record data
*/
public function __construct(object $data = null)
{
$this->data = $data;
}
/**
* Method returns record's raw data
*
* @return object record's raw data
*/
public function getData(): object
{
return $this->data;
}
/**
* Method asserts that data was loaded
*/
private function assertDataWasLoaded(): void
{
if ($this->data=== null) {
throw (new \Exception('Data was not loaded', - 1));
}
}
/**
* Method deletes record
*
* @return int id of the deleted record
*/
public function delete(): int
{
$this->assertDataWasLoaded();
static::deleteById($answerId = Fetcher::getField($this->answer, 'id'));
$this->answer = null;
return $answerId;
}
/**
* Method returns field value
*
* @param string $fieldName
* field name
* @return mixed field value
*/
private function getField(string $fieldName)
{
$this->assertDataWasLoaded();
return Fetcher::getField($this->data, $fieldName);
}
/**
* Method deletes single record
*
* @param int $id
* answers's id
*/
public static function deleteById(int $id): void
{
static::getConnection()->prepare('DELETE FROM %table name% WHERE id = :id');
static::getConnection()->bindParameter(':%primary index field name%', $id, \PDO::PARAM_INT);
static::getConnection()->execute();
}
}
Note that %Table name% is a table name wich starts from big letter. For example we have table 'user' and %Table name% will be 'User'.