简体   繁体   中英

Phalcon Micro Collection Routes not matching

I am trying to create a simple api with phalcon micro , but I am not getting it to work. On the Url /todo/ the controller should be called.

index.php

$di  = new \Phalcon\Di\FactoryDefault;

$di->set('url', function() {
    $url = new \Phalcon\Mvc\Url();
    $url->setBaseUri('/');

    return $url;
});

$di->set('collections', function() {
    $collection = new \Phalcon\Mvc\Micro\Collection();

    $collection->setHandler(SimpleToDo\Controller\ApiController::class, true);
    $collection->setPrefix('/todo');
    $collection->get('/', 'index');

    return [$collection];
});

$app = new \Phalcon\Mvc\Micro();
$app->setDI($di);

foreach($di->get('collections') as $collection) {
    $app->mount($collection);
}

$app->notFound(function () use ($app) {
    $app
    ->response
    ->setStatusCode(404, 'Not Found')
    ->sendHeaders();
});

$app->handle();

ApiController.php

<?php

namespace SimpleToDo\Controller;

class ApiController
{
    public function index()
    {
    echo 'Hello World!';
    }
}

I faced the same problem a few times back, but I come to the solution like this.

you have to initiate the routing in your services.php file like below:

protected function initRouter() {
    return include __DIR__ . '/config/routes.php';
}

You just need to create the routes.php file in which you have to write the code for you required routing. This will serve you request and you can customize your URL accordingly.

   use Phalcon\Mvc\Router;
   // Create the router
   $router = new Router();

   $router->add("/yourPrefferedUrl", array(
       "controller" => "controllerName",
       "action" => "methodeName"
   ));

you can add code for multiple requests, you just need to copy the same code, and just change the controller and method. This way you can try to use Controller which are located in separate files and not a single PHP file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM