Api Components
A trustworthy backend
With all the capabilities of neoan3, using the framework as a pure backend has been the most common use case. As production ready, testable development of APIs is possible within the same time as scaffolding and mocking would take, it is clear why this use-case is so popular. As all functional restrictions and assumptions have already been presented in API routing, we want to present some common examples here.
Restricting access
PHP7.4
//... in api component "post", assuming the use of JwtWrapper provider as "auth"
// define update endpoint
function putPost($body)
{
// throw a 401 authenticated response when no valid authentication is present
// otherwise, assign the json web token content to $jwt
$jwt = $this->provider['auth']->restrict();
$model = $this->loadModel(PostModel::class);
// check if currently authenticated user is the owner of the post
if($model::get($body['id'])['user_id'] !== $jwt->getUserId()){
throw new RouteException('no permission to edit this entry', 401);
}
// all checks ok? Then update post
return $model::update($body);
}
PHP8
//... in api component "post", assuming the use of JwtWrapper provider as "auth"
// define update endpoint
// throw a 401 authenticated response when no valid authentication is present
// otherwise, assign the json web token content to the frame's $auth
#[Authorization('restrict')]
// initialize model
#[InitModel(PostModel::class)]
function putPost($body)
{
// check if currently authenticated user is the owner of the post
if(PostModel::get($body['id'])['user_id'] !== $this->auth->getUserId()){
throw new RouteException('no permission to edit this entry', 401);
}
// all checks ok? Then update post
return PostModel::update($body);
}
Using parameters conditionally
PHP7.4
function getPost($id = null, $search = [])
{
$model = $this->loadModel(PostModel::class);
// reacting to e.g. /api.v1/post/123ABC123ABC
if($id){
return $model::get($id);
}
// reacting to e.g. /api.v1/post?slug=my-post
return $model::find($search);
}
PHP8
#[InitModel(PostModel::class)]
function getPost($id = null, $search = [])
{
// reacting to e.g. /api.v1/post/123ABC123ABC
if($id){
return PostModel::get($id);
}
// reacting to e.g. /api.v1/post?slug=my-post
return PostModel::find($search);
}