How to SET service "db" in Controller and access in action other

Hi Phalcon, Long time no see. I have a prolem, Because request, I want to set service in controller infoDbAction and access it.

When i redirect to page adminAccount this error:

Please see code:

 <?php
 public function infoDbAction() {
        if ($this->request->isPost()) {
            $messages = '';
            $params = array_merge($this->request->getPost(), $_FILES);
            try {
                $info = [
                    "adapter" => "Mysql",
                    "host" => $params['dbhost'],
                    "username" => $params['uname'],
                    "password" => $params['pwd'],
                    "dbname" => $params['dbname']
                ];
                $db = new \Phalcon\Db\Adapter\Pdo\Mysql($info);
                if ($db) {
                    $di = $this->getDI();
                    $di->set(
                        "db",
                        function () use($info) {
                            return new \Phalcon\Db\Adapter\Pdo\Mysql(
                                $info
                            );
                        }
                    );
                    $this->response->redirect('index/adminAccount');
                    //$this->di->get("db");
                    //$this->view->disable();
                }
            } catch (Exception $e) {
                $messages = '<b>Error when initializing database connection:</b>' . $e->getMessage();
            }
        }
        $this->view->messages = $messages;
    }

    public function adminAccountAction() {
        //$this->di->get("db");
        //this error
        $db = $this->getDI()->get('db');
        /*$sql = "INSERT INTO user (name) VALUE (?)";
        $db->execute($sql, ['aaaa']);*/
    }

Please help me, thanks you



1.7k

You must call infoDbAction method before you access to db service since you register there in $di. Or make some protected method that will set db service and call in each action before access to db

This is normal, when you redirect to another page you loose your object ... you need to use a services file regrouping all you services which included for each request like you should do for your route service.
Example :
https://github.com/corentin-begne/phalconTool/blob/master/templates/project/app/config/services.php

I strongly believe this leads to spaghetti code. There's a reason why we use IoC pattern - global services definition.

But if you really need to do something like that, you'd need to stick to PHP basics, i.e. you need to use onConstruct() (Phalcon) or __construct() (PHP) method to initialize your "shared" object, thus, all methods in your class/controller will have access to that object.

Loosely ties here, but it's also important to note (i pulled my hair out until Jurigag helped me), that if you change a service definition ($di->set...), all consecutive calls to $this->db (controller context for eg.) will still point to the OLD definition. You'll have to issue unset($this->db) before using it again!

edited Jan '17

He is doing redirect anyway so he don't even have db from old request set.

PHP doesn't know ANYTHING about objects set in other requests. At least not out of box. Each request = other objects, other di etc etc etc. Do you even know how php works? Maybe it's start to read https://secure.php.net/docs.php before starting frameworks? It could really save you a time.

Loosely ties here, but it's also important to note (i pulled my hair out until Jurigag helped me), that if you change a service definition ($di->set...), all consecutive calls to $this->db (controller context for eg.) will still point to the OLD definition. You'll have to issue unset($this->db) before using it again!

Thank for support, I using connect database with PDO. I will examine this issue when I have free time. With phalcon I build to Create website online and CMS, it wonderfull. I'm from Viet Nam Thank you very much Please review project at https://forum.phalconphp.com/discussion/15359/my-cms-phalcon-3