We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

what is the proper source code for Tutorial 3: Creating a Simple REST API?

hi, I am new. When I tried the Tutorial 3 in the official document. I cannot make it work. I don't know or see a proper complete set of source code either. I guess my problem should be in the root index.php as ( https://localhost/my-rest-api/api/robots/ ) :

<?php
// Use Loader() to autoload our model
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(
    __DIR__ . '/models/'
))->register();
$di = new \Phalcon\DI\FactoryDefault();
//Set up the database service
$di->set('db', function(){
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host" => "localhost",
        "username" => "root",
        "password" => "tm3456",
        "dbname" => "robotics"
    ));
});
$app = new \Phalcon\Mvc\Micro($di);
//Retrieves all robots
$app->get('/api/robots', function() {
    $phql = "SELECT * FROM Robots ORDER BY name";    
    $robots = $app->modelsManager->executeQuery($phql);  // <<<<---- the following line then error: Undefined variable app
    $data = array();
    foreach ($robots as $robot) {
        $data[] = array(
            'id' => $robot->id,
            'name' => $robot->name,
        );
    }
    echo json_encode($data);
});
edited Mar '14

Hi,
You have to pass $app to your function() namespace

$app->get('/api/robots', function() use ($app) {

}