Skip to content

Instantly share code, notes, and snippets.

@mannysoft
Created September 1, 2014 09:35
Show Gist options
  • Save mannysoft/806c23aca2b78bdb0690 to your computer and use it in GitHub Desktop.
Save mannysoft/806c23aca2b78bdb0690 to your computer and use it in GitHub Desktop.
<?php
class DataCreator{
protected $listener;
protected $department;
protected $redirectPage;
public function __construct($listener, $model = '', $redirectPage = '', $labels = array())
{
$this->listener = $listener;
$this->model = $model;
$this->redirectPage = $redirectPage;
$this->labels = $labels;
}
public function fill($listener, $model = '', $redirectPage = '')
{
$this->listener = $listener;
$this->model = $model;
$this->redirectPage = $redirectPage;
$this->labels = $labels;
}
public function create($input, $id = NULL)
{
if (isset($input['op']))
{
$m = $this->model->fill($input);
// Use for users
if (array_key_exists('password', $input))
{
$m->password = $input['password'] == '' ? '' : md5($input['password']);
}
if ($m->save())
{
return $this->listener->creationSucceedsRedirect($this->redirectPage);
}
return $this->listener->creationFails($m->errors, 'add', $this->redirectPage, $this->labels);
}
return $this->listener->defaultView([], 'add', $this->redirectPage, '', $this->labels);
}
public function edit($input, $id = NULL)
{
$errors = [];
if (isset($input['op']))
{
$m = $this->model->find($id);
// Use for users
if (array_key_exists('password', $input))
{
if ($input['password'] != '')
{
$m->password = md5($input['password']);
}
unset($input['password']);
}
$m->fill($input);
if ($m->save())
{
return $this->listener->creationSucceedsRedirect($this->redirectPage);
}
$errors = $m->errors;
}
$row = $this->model->find($id);
return $this->listener->defaultView($errors, 'edit', $this->redirectPage, $row, $this->labels);
}
public function apiCreate($input, $id = NULL)
{
$m = $this->model->fill($input);
if ($m->save())
{
return $this->listener->apiCreationSucceeds($data = []);
}
return $this->listener->apiCreationFails($m->errors);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment