Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Service 'db' was not found

Using the following within the module.php

$di->setShared('db', function() use ($config){
    return new DbAdapter(array(
                "host" => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname" => $config->database->dbname,
            ));
});

Within my controller I can use the following and I can see it gets the 'db' service:

$db = $this->getDI()->get('db');

and it returns the correct object. However when I try to access a model it returns an exception:

    Service 'db' was not found in the dependency injection container


31.0k

Hey man

What is version Phalcon ? or try code below:

// Database connection is created based in the parameters defined in the configuration file
$di->set(
    'db',
    function () use ($di) {
        return new Mysql([
            'host'     => $di->get('config')->database->mysql->host,
            'username' => $di->get('config')->database->mysql->username,
            'password' => $di->get('config')->database->mysql->password,
            'dbname'   => $di->get('config')->database->mysql->dbname,
            'schema'   => $di->get('config')->database->mysql->schema,
            'options'  => array(
                \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $di->get('config')->database->mysql->charset
            )
        ]);
    },
    true // shared
);

It working for me

Thanks for the reply. Have tried it with your code and still get the same exception.

Version is 2.0.0

This is what my Module.php registerServices code looks like:

 public function registerServices(\Phalcon\DiInterface $di)
{

    /**
     * Read configuration
     */
    $config = new Ini(__DIR__ . "/config/config.ini");

    /**
     * Setting up the view component
     */
    $di['view'] = function () {
        $view = new View();
        $view->setViewsDir(__DIR__ . '/views/');

        return $view;
    };

    /**
     * Database connection is created based in the parameters defined in the configuration file
     */

    $di->set(
        'db',
        function () use ($config) {
            return new Mysql([
                "host" => $config->database->host,
                "username" => $config->database->username,
                "password" => $config->database->password,
                "dbname" => $config->database->dbname,
            ]);
        },
        true // shared
    );

    /**
     * The URL component is used to generate all kind of urls in the application
     */
    $di->set('url', function() use ($config){
        $url = new Url();
        $url->setBaseUri('/');
        return $url;
    });

    $di->set('dispatcher', function () {

        $eventsManager = new EventsManager;

        /**
         * Check if the user is allowed to access certain action using the SecurityPlugin
         */
        $eventsManager->attach('dispatch:beforeDispatch', new SecurityPlugin);

        /**
         * Handle exceptions and not-found exceptions using NotFoundPlugin
         */         

        $dispatcher = new Dispatcher;
        $dispatcher->setEventsManager($eventsManager);

        $dispatcher->setDefaultNamespace('Phalcontest\Frontend\Controllers');

        return $dispatcher;
    });
}

and again when I debug within a controller and do a $di->get('db') it returns a valid mysql object?



31.0k

Yes

You try code below if it weren't working. I think that bug in Phalcon 2.0

    #case 1
    $pdo = \Phalcon\DI::getDefault()->getDb();
    #case 2
    $this->getDI()->getDb()

Case 2 returns a valid object.

However when I now try to access a model using Model::findFirst() I still get the same db exception?

Thanks for the help



31.0k

Can you upload code ?

public function startAction() { if ($this->request->isPost()) {

        $username      = $this->request->getPost('username');
        $password   = $this->request->getPost('password');

        $db = $this->getDI()->get('db');
        $db2 = $this->getDI()->getDb();

        $user = User::findFirst(array(
            "username = :user: AND password = :password:",
            'bind' => array('user' => $username, 'password' => sha1($password))
        ));
        if ($user != false) {
            $this->_registerSession($user);
            $this->flash->success('Welcome ' . $user->getUsername());
            return $this->forward('admin/index');
        }

        $this->flash->error('Wrong email/password');
    }

    return $this->forward('/');
}

Both the $db and $db2 variables return a valid Pdo\Mysql object from the looks of it. Its at the User::findFirst() that it throws the exception that 'db' was not found.



31.0k

User::findFirst() that it throws the exception that 'db' was not found.

It mean dependency injection db not registered, I don't know have that becasue according you have defined dependency injectionDB ?

edited Apr '15
$di->set('db', function () use ($config) {

    /*
    return new DbAdapter(array(
        'host' => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname' => $config->database->dbname,
        "charset" => $config->database->charset
    ));
    */

    return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        'host' => $config->database->host,
        'username' => $config->database->username,
        'password' => $config->database->password,
        'dbname' => $config->database->dbname,

    ));
});

Can you try to use PDO Adapter instead of the default Db Adapter? At least DbAdapter doesn't work for me.

Have you considered registered namespace within the model for that module?

try this;

       $di->set('db', function () use ($config) {
        return new Phalcon\Db\Adapter\Pdo\Mysql([
            "host" => $config->database->host,
            "username" => $config->database->username,
            "password" => $config->database->password,
            "dbname" => $config->database->dbname,
        ]);
     },
    true 
    );

Then in your model; test this;

 $db = $this->getDI()->get('db');
edited Apr '15

Thanks for the replies guys, I have had a busy week so not had a chance until now to review.

None of the above suggestions worked unfortunately.

Dominic I do think now that maybe it has something to do with the namespacing. I have actually moved the models folder out off apps so my structure looks like the following:

project/
   - apps/
   - config/
   - models/
   - public/

I can however inside my controlers go $user = new User(); and it works fine so it has registered the model class.

The exact line that it throws the exception is:

public static function findFirst($parameters = null) {}

Which is part of Phalcon so maybe theres a bug in there?

Just to add to that:

Dominic I have tried to create a new User object and added a function to test the:

  $db = $this->getDI()->get('db');

This also throws the exception on a new object.

User::findFirst() that it throws the exception that 'db' was not found.

It mean dependency injection db not registered, I don't know have that becasue according you have defined dependency injectionDB ?

Issue is still open.



1.4k
Accepted
answer

SOLVED

For anyone else looking through this further down the line: I ended up finding a function that defined a new dependency injector so it would overwrite it... so once that happened it no longer had the db service inside of it. One of those dumb ones that you dont spot...