Skip to content

Instantly share code, notes, and snippets.

@konecny
Created July 8, 2012 14:34
Show Gist options
  • Save konecny/3071197 to your computer and use it in GitHub Desktop.
Save konecny/3071197 to your computer and use it in GitHub Desktop.
ajax_return() vrací JSON formát pro JavaScript
<?php
class Controller {
private $json_otuput;
function start() {
try {
$x = new X;
$x->neco();
} catch (MyException $e) {
$text = new Text("cs");
$translated_text = $text->translate($e->processCode());
if ($translated_text === false) {
$this->json_output = $e->getMessage();
} else {
$this->json_output = $translated_text;
}
}
return $this->__toString();
}
function __toString()
{
return $this->json_output;
}
}
?>
<?php
function __autoload($class){
include $class.'.class.php';
}
function ajax_return($error, $callback) {
return json_encode(array(
"error" => $error,
"callback" => $callback
));
}
try {
$x = new Controller;
$x->start();
} catch (MyException $e) {
echo $e->process(),"\n <br />";
echo $e->processCode(),"\n <br />";
echo $e,"\n";
}
?>
<?php
class Log {
public static function logError($error_msg) {
// Vložení zprávy do souboru nebo databáze
}
}
?>
<?php
class MyException extends Exception {
protected $code;
private $method;
private $e;
function __construct($method, $code=0, $e= NULL) {
$this->method = $method;
$this->code = $code;
if(is_null($e))
$e=new Exception();
$this->e = $e;
parent::__construct($method.' '.$e->getMessage(), $code, $e);
}
function process() {
return $this->method . ":" . strtok($this->e->getMessage(),":");
}
function processCode() {
return $this->method . "({$this->code}):" . strtok($this->e->getMessage(),":");
}
function __toString() {
return $this->method . ":" . $this->e->getMessage();
}
}
?>
<?php
class Text {
private $lang;
function __construct($lang) {
$this->lang = $lang;
}
public function translate($text) {
// nalezení textu v DB
// pri neúspěchu se chyba zaloguje
}
}
?>
<?php
class X {
function neco() {
try {
$pdo = @new PDO("sqlite:test.db", null, null, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$pdo->query("INSERT INTO test VALUES (10)");
} catch (PDOException $e) {
throw new MyException(__METHOD__, 444, $e);
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment