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

Using $app and its dependencies inside a Micro Controller

I am using Micro framework and in order to have a better organization I am using Controllers:

...
$app['db'] = function () {
    return new MysqlAdapter(
        [
            'host'     => 'localhost',
            'username' => 'root',
            'password' => '123',
            'dbname'   => 'blog',
        ]
    );
};

/* Main controller routes */
$mainController = new MicroCollection();
$mainController->setHandler(new MainController());
$mainController->setPrefix('/');

$mainController->get('', 'index');
$mainController->get('doc', 'doc');

$app->mount($mainController);
...

Now inside controllers I want to use the $app object. I have created a token property and a database connection for the $app and I want to use them inside my controller.

How should I access $app inside controller?

<?php
use Phalcon\Mvc\Micro;
use Phalcon\Mvc\Controller;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlAdapter;

class MainController  extends Controller{

    public function index()
    {
        $content = '<h1>Welcome!</h1> token: '. $this->token ."<br>";
        $this->response->setContent($content);

        return $this->response;
    }

    public function doc()
    {
        $content = '<h1>api-documentation!</h1>';
        $this->response->setContent($content);

        return $this->response;
    }

}

Hi @wmac why you don't use DI?



5.5k

Hi and thanks. But in that example, we still need the $app in order to access its dependencies, right? Do I have access to $app Inside controllers?



145.0k
Accepted
answer
edited Jan '18

Add $app to DI as app service. And then access it with $this->app in controller.

edited Nov '20

Add $app to DI as app service. And then access it with $this->app in controller.

Could you please explain how exactly should I add $app to DI as app service?