Lately,i have been toying around with angularjs,and i have to confess,its quite a powerful framework.My side of the story.
Anyway,after reading much online here is my generic factory for consuming APIs(PHP SLIM 3).
Anyway,after reading much online here is my generic factory for consuming APIs(PHP SLIM 3).
app.factory("Data",['$resource','toaster',
function($resource,toaster)
{
var serviceBase='http://localhost/bookroom/school.php';//url
return function(link) //receive part of url with parameters
{
return $resource(serviceBase+link,{},{
query:{method:'GET',isArray:true},//this is for get
update:{method:'PUT'},
delete:{method:'DELETE'},
create:{method:'POST'},
two_query:{
url:serviceBase+link,
method:'GET',isArray:false,
params:{id:'@id',
users_id:'@users_id'
}
}
}
);
}}]);
This is how it is used.
In your controllers
app.controller('usersCtrl',function($scope,$rootScope,$routeParams,$location,$http,Data)
{
$scope.login={};
$scope.msgbox={};
$scope.doLogin=function(users)
{
Data('/login').create({users:users},function(response){
if(response.message=="error")
{
//Do something
}else
{
$location.path('dashboard');
}
}).$promise;
}
$scope.doUserRegister=function(user)
{
var user=Data('/input').create({data:user,id:1},function(response){
$scope.users=response;
console.log($scope.users);
}).$promise;
}});
app.controller('userdisplayCtrl',function($scope,$rootScope,$routeParams,$location,$http,Data)
{
$scope.users={};
Data('/show/:id').query({id: 1},function(response)
{
$scope.users=response;
console.log($scope.users);
}).$promise;
}});
//This is while sending twoparameters
Data('/show_2/:id/:users_id').two_query({id: 1,users_id:$routeParams.users_id},function(response){
$scope.users=response;
console.log(response.email);
}).$promise;
});
I have not yet used PUT AND DELETE yet.Am quite uncomfortable with them
The rest api is like this, at the root of your site folder:
$app->post('/input', function ($req,$res, $args = []) use($val,$mesg,$help,$get_table)
{
$id = $req->getParsedBody()['id']; //checks both _GET and _POST [NOT PSR-7 Compliant]
$data = $req->getParsedBody()['data'];
$table=get_table($id);//do something
});
$app->get('/show/{id}',function($req,$res,$args)use($val,$mesg,$get_table)
{
$id=$req->getAttribute('id');
$table=get_table($id);
//Do something
});$app->get('/show_2/{id}/{users_id}',function($req,$res,$args)use($val,$mesg,$get_table)
{
$id=$req->getAttribute('id');
$users_id=$req->getAttribute('users_id');
$table=get_table($id);
//do something});
The get_table() is a little function i built to allow me select tables in my simple database
function get_table($id="")
{
if($id==1)
return "admins";
elseif($id==2)
return "students";
elseif($id==3)
return "hostels";
elseif($id==4)
return "lecturers";
}
$get_table=get_table();
If you do not understand,Please comment below and i will try help explain.Great weak