Просмотр файла vkclone-0.0.1/protected/components/CrudControllerBehavior.php

Размер файла: 2.43Kb
<?php
class CrudControllerBehavior extends ControllerBehavior {
	/**
	 * ActiveRecord class
	 * @var string
	 */
	public $modelClass;
	/**
	 * Query param
	 * @var string
	 */
	public $key = 'id';
	/**
	 * ActiveRecord model
	 * @var CActiveRecord
	 */
	protected $_model;
	/**
	 * Alert messages
	 * @var string
	 */
	public $updateSuccessfullAlert = 'Successfully updated';
	public $deleteSuccessfullAlert = 'Successfully deleted';
	public $deleteFailureAlert = 'An error occured during deleting';
	/**
	 * Url is used to redirect user after delete action
	 * @var array|string|callable
	 */
	public $deleteContinueUrl = '/';

	/**
	 * Returns model
	 * @return CActiveRecord model
	 */
	public function getModel() {
		if ($this->_model === null)
			$this->retrieveRecord();
		return $this->_model;
	}

	/**
	 * Shows model
	 */
	public function actionIndex() {
		$this->owner->render('index', array(
			'model' => $this->model,
		));
	}

	/**
	 * Updates model
	 */
	public function actionUpdate() {
		$model = $this->model;
		$model->setScenario('update');
		if (isset($_POST[CHtml::modelName($model)])) {
			$model->attributes = $_POST[CHtml::modelName($model)];
			if ($model->save()) {
				Yii::app()->user->setAlert($this->updateSuccessfullAlert, 'success');
				$this->owner->redirect(array('index', 'id' => $model->id));
			}
		}

		$this->owner->render('update', array(
			'model' => $model,
		));
	}

	/**
	 * Renders form to confirm deletion
	 */
	public function actionConfirm() {
		$this->owner->render('confirm', array(
			'model' => $this->model,
		));
	}

	/**
	 * Deletes model
	 */
	public function actionDelete() {
		$url = is_callable($this->deleteContinueUrl)
			? call_user_func($this->deleteContinueUrl, $this->model)
			: $this->deleteContinueUrl;

		if ($this->model->delete()) {
			Yii::app()->user->setAlert($this->deleteSuccessfullAlert, 'success');
			$this->owner->redirect($url);
		} else {
			Yii::app()->user->setAlert($this->deleteFailureAlert, 'danger');
			$this->owner->redirect(array('confirm', 'id' => $this->model->id));
		}
	}

	/**
	 * Retrieves record by id
	 */
	protected function retrieveRecord() {
		if (($id = Yii::app()->request->getQuery($this->key, null)) === null)
			$this->showRestriction();

		$model = $this->modelClass;
		if (($this->_model = $model::model()->findByPk($id)) === null)
			$this->showRestriction();
	}

	/**
	 * Shows a restriction
	 */
	protected function showRestriction() {
		throw new CHttpException(404);
	}
}