Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Last active December 21, 2015 01:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonuexe/577d089815e241d5da26 to your computer and use it in GitHub Desktop.
Save zonuexe/577d089815e241d5da26 to your computer and use it in GitHub Desktop.
PHP AppRunner
<?php
/**
* @copyright 2015 pixiv Inc.
* @license http://creativecommons.org/publicdomain/zero/1.0/legalcode CC0-1.0
*/
final class AppRunnerSample
{
public static function execute(ControllerTypeBInterface $controller)
{
try {
if (TEST_SERVER) {
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
$whoops->register();
}
$controller::main();
} catch (UserException $exception) { // 404とか403を送出する種類のパターンをキャッチ
self::setHttpStatus($exception::HTTP_STATUS_CODE);
// 投げられた例外に付随するパラメータ
$params = $exception->getParams();
// エラーコードのデフォルトパラメータ
$params += ErrorCode::getParamsFromCode($exception->getErrorCode());
self::displayError($params);
} catch (HogeException $exception) { // 任意の例外のエラーハンドリング
self::setHttpStatus($exception::HTTP_STATUS_CODE);
// 投げられた例外に付随するパラメータ
$params = $exception->getParams();
// エラーコードのデフォルトパラメータ
$params += ErrorCode::getParamsFromCode($exception->getErrorCode());
self::displayError($params);
} catch (Exception $exception) { // PHP7ではThrowableにする
// TEST_SERVERはpixivの開発環境でtrueになる
if (TEST_SERVER) {
your_own_exception_logging($exception);
throw $exception;
}
your_own_exception_logging($exception);
self::setHttpStatus(500);
self::displayError(['msg' => 'Error']);
}
}
private static function setHttpStatus($status_num)
{
if (!headers_sent()) {
http_response_code($status_num);
}
}
public static function displayError($params)
{
$smarty = new Smarty;
// ...
}
}
<?php
/**
* @copyright 2015 pixiv Inc.
* @license http://creativecommons.org/publicdomain/zero/1.0/legalcode CC0-1.0
*/
interface ControllerTypeBInterface
{
public static function main();
}
<?php
require_once dirname(__DIR__) . '/inc/init.php';
/**
* @copyright 2015 pixiv Inc.
* @license http://creativecommons.org/publicdomain/zero/1.0/legalcode CC0-1.0
*/
final class HogeController implements ControllerTypeBInterface
{
public static function main()
{
// ...
}
}
AppRunnerSample::execute(new HogeController);
exit();
Copyright 2015 pixiv Inc.
CC0 http://creativecommons.org/publicdomain/zero/1.0/legalcode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment