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

How to use Phalcon\Mvc\Micro echo a view?

Hi, When I use Collection as a route in my application,but I can't echo a template view by using Phalcon\Mvc\Micro() and Phalcon\Mvc\Micro\Collection(). And here is my demo. Directory Structure:

      app
           controller
                TestController.php
            views
                  test.phtml
       public
            index.php

index.php code is:

          $di = new \Phalcon\DI\FactoryDefault();
           $di->set('view', function() use ($config) {
           $view = new \Phalcon\Mvc\View();
           $view->setViewsDir(__DIR__ . $config->application->viewsDir);
           $view->registerEngines(array(
            ".phtml" => 'Phalcon\Mvc\View\Engine\Php'
           ));
          return $view;
        });

        $app = new Phalcon\Mvc\Micro();
        $app->setDI($di);
        $collection = new Phalcon\Mvc\Micro\Collection();
        $collection->setHandler(new TestController());
        $collection->get('/', 'index');
        $app->mount($collection);
        $app->handle();

in TestController.php:

Class TestController {

    public function index(){
        $view = new Phalcon\Mvc\View();
        $view->setViewsDir('app/views/test.phtml');

        $view->start();
        $view->finish();

        //Printing views output
        echo $view->getContent();
    }
}

when I run it, it can't work, but if i replace Controller.php index method in this:

    public function index(){
        echo '<h1>OK</h1>'
    }

it works

So, I want to know how to use this echo in a template view.

You can't use setViewsDir() method like this, you're targeting a file and not a directory into your TestController. I think you want uses the method $view->pick() (https://docs.phalcon.io/en/latest/reference/views.html#picking-views). If you are really new with PhalconPHP, maybe you can use or see the source code of the starterKit just here : https://github.com/GesJeremie/Phalcon-starterkit

Have fun :)