Created
August 29, 2018 00:38
-
-
Save iamdaniele/2d884b3636c2323c7f0082a30157bfce to your computer and use it in GitHub Desktop.
An Average Base 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
<?hh | |
class AverageController extends BaseController { | |
// Use this if the user needs a valid login | |
use AuthenticationTrait; | |
protected function init() { | |
// The constructor | |
} | |
// Validate request parameters. For example, if the route is | |
// https://example.com?required=param&optional=42 | |
// this method will determine what parameters to expect. | |
protected function params() { | |
return [ | |
// This is a required parameter | |
BaseParam::StringType('required'), | |
// This is an optional parameters (optionals have a default value) | |
BaseParam::IntType('optional', 1), | |
]; | |
} | |
// This is the core of the controller. It tells the framework what to do. | |
// Methods are executed sequentially. If a method invariants or throws, | |
// it will stop the execution and call renderError(). | |
// If all the methods succeed, Base will call render(). | |
// This way, you only have to write code for your happy path, knowing that | |
// Base will handle the worst case scenario. | |
protected function genFlow() { | |
// From trait | |
$this->authenticateUser(); | |
$this->getData(); | |
$this->logAction(); | |
} | |
protected function getData() { | |
// Something here | |
} | |
protected function logAction() { | |
// Something here | |
} | |
protected function renderError(Exception $e) { | |
return <div>An unexpected error occurred: {$e->getMessage()}</div>; | |
} | |
protected function render() { | |
return <div>Success!</div>; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment