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

rest api example not working my abreviated index.php

I tried to start the tutorial at the rest example (haste makes waste). I just added what I thought was needed to establish a route with some echo statments to make sure I was getting there.

<?php
$app = new \Phalcon\Mvc\Micro();
//define the routes here
//Retrieves all robots
$app->get('/api/robots', function() {
});
//Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function($name) {
});
//Retrieves robots based on primary key
$app->get('/api/robots/{id:[0-9]+}', function($id) {
});
//Adds a new robot
$app->post('/api/robots', function() {
});
//Updates robots based on primary key
$app->put('/api/robots/{id:[0-9]+}', function() {
});
//Deletes robots based on primary key
$app->delete('/api/robots/{id:[0-9]+}', function() {
});
$app->handle();
// Use Loader() to autoload our model
$loader = new \Phalcon\Loader();
$loader->registerDirs(array(
    __DIR__ . '/models/'
))->register();
// echo "dir is ".__DIR__."<br />";exit;
$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" => "asimov",
        "password" => "zeroth",
        "dbname" => "robotics"
    ));
});
//Create and bind the DI to the application
$app = new \Phalcon\Mvc\Micro($di);
//Retrieves all robots
$app->get('/api/robots', function() use ($app) {
    echo "got here OK <after get call br />";
    $phql = "SELECT * FROM Robots ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql);

    $data = array();
    foreach ($robots as $robot) {
        $data[] = array(
            'id' => $robot->id,
            'name' => $robot->name,
        );
    }
    echo json_encode($data);
});
echo "got here OK on exit;<br />\n";


33.8k

Put $app->handle() to the end of the file, maybe that's it.



2.8k

Thanks again that seemed to work. I thought I tried that before, but anyway I will try to complete the example and maybe use one of my own databases to finish the example. I am new to these forums is there anything I should do to give you proper credit for the help?

On Monday, September 8, 2014 10:45 AM, RompePC [email protected] wrote:

Put $app->handle() to the end of the file, maybe that's it. — Reply to this email directly or view the complete thread on Phosphorum. Change your e-mail preferences here



33.8k

handle() serves the content, so first you need to set up everything. You don't build a house starting from the roof, isn't it? hehe

Always set the order of the things the same way the tutorials do, and later, experiment.