Created
October 20, 2017 15:42
-
-
Save holabene/d59adf29c7d085b58e270320ec72b5d3 to your computer and use it in GitHub Desktop.
Concept controller
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 | |
class Controller | |
{ | |
protected $user; | |
protected $service; | |
public function __construct(User $user, Service $service) | |
{ | |
$this->user = $user; | |
$this->service = $service; | |
} | |
public function list(Collection $items): Output | |
{ | |
$output = new Output(); | |
$output->setVariable('items', $items); | |
return $output; | |
} | |
public function get(Item $item): Output | |
{ | |
$output = new Output(); | |
$output->setVariable('item', $item); | |
return $output; | |
} | |
public function create(Input $input): Output | |
{ | |
$item = new Item(); | |
$data = $input->get('data'); | |
try { | |
$service->serialize($item, $data); | |
if (!$service->validate($item)) { | |
throw new Exception('Not valid'); | |
} | |
$service->create($item); | |
$output->notify('alert.success', 'Item created'); | |
$output->setVariable('item', $item); | |
$output->setStatus(Output::STATUS_OK); | |
} catch (Exception $e) { | |
$output->notify('alert.error', 'Failed to create'); | |
$output->notify('log.error', $e->getMessage()); | |
$output->setStatus(Output::STATUS_ERROR); | |
} | |
return $output; | |
} | |
public function update(Item $item, Input $input): Output | |
{ | |
$data = $input->get('data'); | |
try { | |
$service->serialize($item, $data); | |
if (!$service->validate($item)) { | |
throw new Exception('Not valid'); | |
} | |
$service->update($item); | |
$output->notify('alert.success', 'Item updated'); | |
$output->setVariable('item', $item); | |
$output->setStatus(Output::STATUS_OK); | |
} catch (Exception $e) { | |
$output->notify('alert.error', 'Failed to update'); | |
$output->notify('log.error', $e->getMessage()); | |
$output->setStatus(Output::STATUS_ERROR); | |
} | |
return $output; | |
} | |
public function delete(Item $item, Input $input): Output | |
{ | |
$output = new Output(); | |
if (!$input->confirm()) { | |
$output->notify('alert.warning', 'Sure?'); | |
$output->setVariable('item', $item); | |
$output->setStatus(Output::STATUS_OK); | |
return $output; | |
} | |
try { | |
if ($input->cancelled()) { | |
$output->notify('alert.info', 'Delete canceled'); | |
} else { | |
$service->delete($item); | |
$output->notify('alert.success', 'Item deleted'); | |
} | |
$output->setStatus(Output::STATUS_OK); | |
} catch (Exception $e) { | |
$output->notify('alert.error', 'Failed to delete'); | |
$output->notify('log.error', $e->getMessage()); | |
$output->setStatus(Output::STATUS_ERROR); | |
} | |
return $output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment