Skip to content

Instantly share code, notes, and snippets.

@ichiriac
Created August 15, 2012 18:48
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 ichiriac/3362502 to your computer and use it in GitHub Desktop.
Save ichiriac/3362502 to your computer and use it in GitHub Desktop.
A beaba REST sample
<?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' => 'john@doe.com',
'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'] === 'john@doe.com'
&& $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' => 'john@doe.com',
'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