Last active
August 22, 2016 00:34
-
-
Save anton-kotik/52379647ea5dddd0cc5b to your computer and use it in GitHub Desktop.
Simple PHP class template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\Component\Example; | |
use Traversable; | |
use Exception as PhpException; | |
use Application\Component\Exception; | |
use Zend\Stdlib\ArrayUtils; | |
/** | |
* Описание класса. | |
*/ | |
class Example | |
{ | |
/** | |
* @var string | |
*/ | |
protected $text; | |
/** | |
* Устанавливает значения параметров. | |
* | |
* @param array|Traversable $options Ассоциативный массив параметров. | |
* | |
* @return $this | |
* | |
* @throws Exception\InvalidArgumentException | |
*/ | |
public function setOptions($options = []) | |
{ | |
// TODO: Пример задачи под вопросом (?) | |
if ($options instanceof Traversable) { | |
$options = ArrayUtils::iteratorToArray($options); | |
} elseif (!is_array($options)) { | |
throw new Exception\InvalidArgumentException(sprintf( | |
'Значение параметра $options должно быть массивом или %s. Получено %s', | |
Traversable::class, is_object($plugin) ? get_class($plugin) : gettype($plugin) | |
)); | |
} | |
foreach ($options as $name => $value) { | |
$method = 'set' . str_replace(['_', '-'], '', $name); | |
$this->{$method}($value); | |
} | |
return $this; | |
} | |
/** | |
* @param array $data | |
* | |
* @throws Exception\RuntimeException | |
*/ | |
public function throwDataException(/** @noinspection PhpUnusedParameterInspection */ array $data) | |
{ | |
throw new Exception\RuntimeException(sprintf( | |
'Объект класса %s c параметрами %s не найден', | |
static::class, json_encode($where, JSON_UNESCAPED_UNICODE) | |
)); | |
} | |
/** | |
* Преобразовывает объект в строку. | |
* | |
* @return string | |
*/ | |
public function toString() | |
{ | |
return $this->getText(); | |
} | |
/** | |
* Устанавливает значение в недоступное свойство. | |
* | |
* @param string $name Имя свойства. | |
* @param mixed $value Устанавливаемое значение. | |
*/ | |
public function __set($name, $value) | |
{ | |
$this->$name = $value; | |
} | |
/** | |
* Возвращает значение недоступного свойства. | |
* | |
* @param string $name Имя свойства. | |
* | |
* @return mixed | |
*/ | |
public function __get($name) | |
{ | |
if (isset($this->$name)) { | |
return $this->$name; | |
} | |
$trace = debug_backtrace(); | |
trigger_error(sprintf('Неопределенное свойство в __get(): %s в файле %s на строке %d', $name, $trace[0]['file'], $trace[0]['line']), E_USER_NOTICE); | |
return null; | |
} | |
/** | |
* Проверяет, задано ли значение недоступного свойства. | |
* | |
* Метод будет выполнен при использовании isset() или empty() на недоступных свойствах. | |
* | |
* @param string $name Имя свойства. | |
* | |
* @return bool | |
*/ | |
public function __isset($name) | |
{ | |
return isset($this->$name); | |
} | |
/** | |
* Удаляет значение недоступного свойства. | |
* | |
* Метод будет выполнен при вызове unset() на недоступном свойстве. | |
* | |
* @param string $name Имя свойства. | |
*/ | |
public function __unset($name) | |
{ | |
unset($this->$name); | |
} | |
/** | |
* Вызывает недоступный метод в контексте объекта. | |
* | |
* @param string $method Имя метода. | |
* @param array $arguments Массив параметров, переданных в вызываемый метод. | |
* | |
* @return mixed | |
* | |
* @throws Exception\BadMethodCallException | |
*/ | |
public function __call($method, array $arguments) | |
{ | |
if (method_exists($this->test, $method)) { | |
return call_user_func_array([$this->test, $method], $arguments); | |
} | |
throw new Exception\BadMethodCallException(sprintf( | |
'Неизвестный метод %s::%s', static::class, $method | |
)); | |
} | |
/** | |
* Вызывает недоступный метод в статическом контексте. | |
* | |
* @param string $method Имя метода. | |
* @param array $arguments Массив параметров, переданных в вызываемый метод. | |
* | |
* @return mixed | |
* | |
* @throws Exception\BadMethodCallException | |
*/ | |
public function __callStatic($method, array $arguments) | |
{ | |
$instance = static::getInstance(); | |
if (method_exists($instance, $method)) { | |
return call_user_func_array([$instance, $method], $arguments); | |
} | |
throw new Exception\BadMethodCallException(sprintf( | |
'Неизвестный метод %s::%s', get_class($instance), $method | |
)); | |
} | |
/** | |
* Преобразовывает объект в строку. | |
* | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
try { | |
return $this->toString(); | |
} catch (PhpException $e) { | |
trigger_error(sprintf('%s: %s [%s:%d]', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_ERROR); | |
return 'error'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment