Created
August 15, 2012 18:48
-
-
Save ichiriac/3362502 to your computer and use it in GitHub Desktop.
A beaba REST sample
This file contains 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 | |
// include the beaba framework before ... | |
$app = new beaba\core\WebApp(array( | |
'layouts' => array( | |
'profile/view' => function( $app, $data ) { | |
echo '<h1>Profile</h1>'; | |
echo '<p> Name : ' . $data['name'] . '</p>'; | |
echo '<p> Email : ' . $data['email'] . '</p>'; | |
} | |
), | |
'routes' => array( | |
'user-api' => array( | |
'check' => array('equals', '/user'), | |
'callback' => function( $app, $args ) { | |
return array( | |
'GET' => function() use($app) { | |
$data = array( | |
'name' => 'John', | |
'email' => '[email protected]', | |
'age' => '30', | |
'password' => 'secret !!!' | |
); | |
return array( | |
'json' => function() use($data) { | |
// hide the password from json | |
unset($data['password']); | |
return $data; | |
}, | |
'html' => function() use($app, $data) { | |
return $app->getView() | |
->setLayout('simple') | |
->push( | |
'content', 'profile/view', $data | |
) | |
; | |
} | |
); | |
}, | |
'POST' => function() use( $app, $args ) { | |
$errors = array(); | |
if ( empty($args['username']) ) { | |
$errors[] = 'The username is mandatory'; | |
} | |
if ( empty($args['password']) ) { | |
$errors[] = 'The password is mandatory'; | |
} | |
if ( empty($errors) ) { | |
if ( | |
$args['username'] === '[email protected]' | |
&& $args['password'] === 'secret' | |
) { | |
// open a session | |
} else { | |
$errors[] = 'Bad login'; | |
} | |
} | |
return array( | |
'json' => function() use( $errors ) { | |
if ( empty($errors) ) { | |
return array( | |
'result' => true, | |
'redirect' => '/index' | |
); | |
} else { | |
return array( | |
'result' => false, | |
'errors' => $errors | |
); | |
} | |
}, | |
'html' => function() use( $app, $errors ) { | |
if ( empty($errors) ) { | |
throw new \beaba\core\Exception( | |
'/index', 301 | |
); | |
} else { | |
return $app->getView() | |
->setLayout('simple') | |
->push( | |
'content', | |
'profile/login', | |
$errors | |
) | |
; | |
} | |
} | |
); | |
} | |
); | |
} | |
) | |
) | |
)); | |
// testing the API | |
$user_infos = $app->dispatch( | |
'GET', '/user', | |
null, | |
'json' | |
); | |
$login = $app->dispatch( | |
'POST', '/user', | |
array( | |
'username' => '[email protected]', | |
'password' => 'secret' | |
), | |
'json' | |
); | |
$app->getResponse()->write( $user_infos ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment