对多个get request slim框架使用相同的函数

时间:2014-10-13 09:00:20

标签: php function rest get slim

我正在尝试使用超薄框架工作返回一些json数据。

我有以下数据

CREATE TABLE students (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    gender INT
) DEFAULT CHARACTER SET utf8 ENGINE=InnoDB;

示例数据

INSERT INTO students (id, name, gender) VALUES
(1, "John", 1),
(2, "Kate", 2),
(3, "Sarah",2),
(4, "Michelle", 2),
(5, "Scott", 1);

我的php代码如下所示

$app = new Slim();
$app->get('/students', 'getStudents');
$app->run();


function getStudents() {

    $sql = "SELECT * FROM students ORDER BY id";
    try {
        $db = getConnection();
        $stmt = $db->query($sql); 
        $students = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo '{"students": ' . json_encode($students) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

当我转到下面的网址时

http://localhost/api/students

我得到了这个预期。

{"students": 
    [
        {"id":"1","name":"John","gender":"1"},
        {"id":"2","name":"Kate","gender":"2"},
        {"id":"3","name":"Sarah","gender":"2"},
        {"id":"4","name":"Michelle","gender":"2"},
        {"id":"5","name":"Scott","gender":"1"}
    ]
}

我想在请求中添加一些潜在的过滤器。 例如按性别过滤

$app = new Slim();
$app->get('/students', 'getStudents');
$app->get('/students/gender/:gender', 'getStudents');
$app->run();


function getStudents($gender) {
    $filterGender = '';
    if($gender) {
       $filterGender = "WHERE gender =" . $gender;
    }
    $sql = "SELECT * FROM students " . $filterGender . " ORDER BY id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        if($gender) {        
            $stmt->bindParam("gender", $gender, PDO::PARAM_INT);
        }
        $stmt->execute();        
        $students = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;       
        echo '{"students": ' . json_encode($students) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

如果我回来

http://localhost/api/students/gender/1

我得到了这个预期。

{"students": 
    [
        {"id":"1","name":"John","gender":"1"},
        {"id":"5","name":"Scott","gender":"1"}
    ]
}

但是,如果我尝试

http://localhost/api/students

#1 [internal function]: getStudents()<br />
#2 \api\Slim\Route.php(392): call_user_func_array('getStudents', Array)<br />
#3 \api\Slim\Slim.php(1052): Slim_Route->dispatch()<br />
#4 \api\index.php(14): Slim->run()<br />
#5 {main}

我在猜测我的语法

    $app->get('/students', 'getStudents');
    $app->get('/students/gender/:gender', 'getStudents');

第二行是写第一行吗?

如何设置它以便我可以选择将params传递给我的请求,同时使用相同的功能?

1 个答案:

答案 0 :(得分:1)

您需要为函数参数设置默认值。

function getStudents($gender = "")