I'm using https://github.com/chriskacerguis/codeigniter-restserver with codeigniter.
I'm trying to add a resource, and enable a get method with an id.
I added the Users controller which inherits the REST_Controller. I added a few methods, index_get, index_post. They both worked perfectly.
I then attempted to add an id parameter to the index_get function (so you can access a particular user- eg localhost/proj/Users/4 would you give you the user with id 4)
class Users extends REST_Controller {
public function index_get($id) {
echo $id;
}
public function index_post() {
echo "post";
}
}
I then tried, using postman, to access this get method:
localhost/proj/index.php/users/3 but it responded with:
{ "status": false, "error": "Unknown method" }
Any idea how I can fix this?
According to CodeIgniter Rest Server doc, you can access request parameter as below :
$this->get('blah'); // GET param
$this->post('blah'); // POST param
$this->put('blah'); // PUT param
So, Users class should be like that ..
class Api extends REST_Controller {
public function user_get() {
echo $this->get('id');
}
public function user_post() {
echo $this->post('id');
}
}
When you test with postman, you can request as below :
For get method,
http://localhost/proj/api/user?id=3
http://localhost/proj/api/user/id/3
For post method,
http://localhost/proj/api/user
form-data : [id : 2]
Hope, it will be useful for you.
I've such trouble and this solution worked for me.
For example, you have a controller file called Api.php like this:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use chriskacerguis\RestServer\RestController;
class Api extends RestController {
function __construct() {
parent::__construct();
}
function user_get($id) {
echo $id;
}
function user_put() {
}
function user_post() {
}
function user_delete() {
}
}
/* End of file Api.php */
/* Location: ./application/controllers/Api.php */
On the browser, you don't need to write http://localhost/api/user_get/1, instead, http://localhost/api/user/1, where 1 is [:id,] because the word _get, _put, _post, or _delete after the word user is the method. So, if you're using the get method, you should write your function in a class like this eg. user_get, users_get, students_get, etc.
Hope it can solve your issue.
Related
I have some validation methods that I need to use for multiple models. For example validation of phone numbers can be shared across multiple models.
I understand from http://www.yiiframework.com/wiki/56/ I can create an extension that can be used by multiple models, for example:
array('phone', 'ext.Validate.Validate'),
I have modified this line a few times and can confirm it is hitting the right file.
With the following in Validate.php
class Validate
I get the error Call to undefined method Validate::applyTo(), therefore I have changed it to
class Validate extends CValidator
As suggested by the link above, however I now get the error:
Class Validate contains 1 abstract method
Here is the file as it stands:
<?php
class Validate extends CValidator
{
public function phone($phone)
{
if(!ctype_digit($phone))
{
$this->addError($phone, Yii::t('flash','flash.not_authorised',array('{attribute}'=>$phone)).' '.ucfirst(str_replace('_', ' ', $phone)).' field');
}
else
{
return true;
}
}
}
Can someone point me in the right direction as to how I can have a shared validation between multiple methods using the above.
Ok I managed to solve this.
I found the following after a few hours of searching http://www.yiiframework.com/wiki/56/
The main issue is tat you need the following method in your class, when extending CValidator:
protected function validateAttribute($object,$attribute)
{
}
Here is the model code (yii/protected/extension/Validate/Validate.php)
array('phone', 'ext.Validate.Validate'),
Here is the class code:
<?php
class Validate extends CValidator
{
protected function validateAttribute($object,$attribute)
{
self::{$attribute."Validation"}($object,$attribute);
}
protected function phoneValidation($object,$attribute)
{
if(!empty($object->$attribute))
{
if(!ctype_digit($object->$attribute))
{
$this->addError($object,$attribute,Yii::t('app','validation.telephon_failed',array('{attribute}'=>ucwords($attribute))));
}
}
}
}
This is my controller
class CarsController extends Controller {
public function actionIndex() {
echo 1; exit();
}
}
this is the module file:
<?php
class CarsModule extends CWebModule {
public $defaultController = "cars";
public function init() {
// this method is called when the module is being created
// you may place code here to customize the module or the application
// import the module-level models and components
$this->setImport(array(
'cars.models.*',
'cars.components.*',
));
}
public function beforeControllerAction($controller, $action) {
if (parent::beforeControllerAction($controller, $action)) {
// this method is called before any module controller action is performed
// you may place customized code here
return true;
}
else
return false;
}
}
my problem is if I access my project like: localhost/cars it works. If I access localhost/cars/index I am getting this message: Unable to resolve the request . If I create a new function and I access like this: localhost/cars/myfunction, still the same. I am working on Windows. Can someone help me with this ?
Typically the default url rule for modules is module/controller/actin, so for access actionIndex inside CarsController inside CarsModule, your url should be localhost/cars/cars/index, not localhost/cars/index. If you don't like the url be like localhost/cars/cars/index, you can write one url manager rule to map localhost/cars/cars/index into localhost/cars/index. Something like this:
'cars/index' => 'cars/cars/index'
I'm using backbone and CodeIgniter Rest Server,
The post and get requests from backbone works fine
But the put and delete requester gets 404 error with the response of {"status":false,"error":"Unknown method."}
edit: I changed the source code to see which method codeigniter is trying to run
my controller url is
http://local/host/impacto/index.php/interviews/
the put request url is
http://localhost/impacto/index.php/interviews/13
and the function that codeigniter is running is 13_put instead of input_put
My controller
class Interview extends REST_Controller {
function __construct(){
parent:: __construct();
}
public function index_get(){
echo "get";
}
public function index_post(){
echo "post";
}
public function index_put($id){
echo "update: " . $id;
}
public function index_delete($id){
echo "delete: " . $id;
}
}
I had the same problem. Accordingly, it's not an error - https://github.com/philsturgeon/codeigniter-restserver/issues/255 - you have to either overtly specify "index" as the function ("Interview/index/{id}"), or alternatively give your method a name ("rest_put($id)", so accessed Interview/rest/{id}")
I have been developing using non framework for about 3 years and I have heard about PHP framework codeigniter.
I think I missed something using this framework which is used for API for my mobile application.
I've facing some problem to get data from database using Phil's CI framework, RESTful plugin. My browser shows error code:
{"status":false,"error":"Unknown method."}
Using my logic below:
controller: user.php
<?php
require(APPPATH.'libraries/REST_Controller.php');
class User extends REST_Controller{
public function user_get()
{
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
//CHECK TO MODEL FUNCTION
$user = $this->user_model->get_user($this->get('id'));
//IF USER EXIST
if($user)
{
$this->response($user, 200); // 200 being the HTTP response code
}
}
public function user_put()
{
// create a new user and respond with a status/errors
}
public function user_post()
{
// update an existing user and respond with a status/errors
}
public function user_delete()
{
// delete a user and respond with a status/errors
}
}
?>
model: user_model.php
<?php
class User_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_user($id){
$query = $this->db->get('mt_user', array('idmt_user'=>$id));
return $query->row_array();
}
}
?>
i'm accessing the database which is has this rows:
idmt_user,username,password, emails, createdate
accessed using mozilla:
#http://localhost/<project>/index.php/user/<userid>
Where's the error(s) ?
thanks.
update,
i am already defined the autoloads for database. But this problem still persist. Is there any helps? thanks
as stated below in answer, i tried to access the url, /user/get_user/ but still showing the same result. Is there any problem using idmt_user in database?
Insert in controllers:
function __construct() {
parent::__construct();
$this->load->model('user_model');
}
And try this route:
http://localhost//index.php/user/user/id/
I believe that the url you are accessing with is wrong.. Try accessing with the url #http://localhost/<project>/index.php/user/<method_name>/<user_id>
Another way of doing it would be using the URI Class.
Instead of writing the following:
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
Changed to:
$userid = $this->uri->segment(3);
Would be 3 based off the url being http://localhost/<project>/user/<method_name>/<user_id>
Reference for URI Class: http://www.codeigniter.com/user_guide/libraries/uri.html
In order to use $this->get(); there would have to be a query parameter to get. Example: id=
If you are passing query parameters than you could store these values in a array as shown below.
if(!empty($this->get()))
{
$params[] = $this->get();
}
I hope this helps.
You should to try include your model file into your controller file by using a __construct() function, like this:
function __construct(){
parent::__construct();
$this->load->model(array('user_model'));
}
i want to give access only to the authorized users
so i wrote the authentication code in the construct method
here is my code
class cp extends CI_Controller {
public function __construct(){
parent::__construct();
$this->this_mustbe_admin();
}
public function this_mustbe_admin()
{
$this->load->model('m_cp');
$md = $this->m_cp->is_admin();
if($md)
return $md;
else
{
redirect(base_url().'cp/login/');
}
}
function login()
{
$this->load->view('admin/login');
}
but i get error
The page isn't redirecting properly
if i remove this_mustbe_admin method from construct and put it on the other controllers it works fine
function do_stuff(){
$this->this_mustbe_admin();
// do stuff
}
but this way i have to write it in each and every one of my methods
You doing circular redirection. An imaginary stack trace:
http request to /cp/
__construct()
this->this_mustbe_admin() -> redirect to /cp/login
http request to /cp/login
__construct()
this->this_mustbe_admin() -> GOTO 3.
You will have to check what method you are trying to execute in your __construct before doing the redirection generating command.
if (!$this->router->method != 'login') {
$this->this_mustbe_admin();
}
Try to write like this
redirect('base_url(cp/login)');
i hope may it wrks....or simply give
redirect('cp/login');
because i got when i used like this