phalcon/cphalcon · error · Phalcon\Container\Exceptions\InstanceNotFound

Instance '{name}' not found

Error message

Instance '{name}' not found

What it means

getInstance() returns only shared instances the container has already built and cached during a resolving get(). It throws InstanceNotFound when no built instance exists under that name yet — merely registering a definition is not enough, and definitions resolved through $new() (cache=false) are never stored.

Source

Thrown at phalcon/Container/Container.zep:269

        if (!array_key_exists(name, this->services)) {
            throw new ServiceNotFound(name);
        }

        return this->services[name];
    }

    /**
     * Return a stored instance
     *
     * @param string $name
     *
     * @return object
     * @throws InstanceNotFound
     */
    public function getInstance(string name) -> object
    {
        if (!array_key_exists(name, this->instances)) {
            throw new InstanceNotFound(name);
        }

        return this->instances[name];
    }

    /**
     * Return a parameter
     *
     * @param string $name
     *
     * @return mixed
     * @throws ParameterNotFound
     */
    public function getParameter(string name) -> mixed
    {
        if (!array_key_exists(name, this->parameters)) {
            throw new ParameterNotFound(name);
        }

View on GitHub (pinned to b7419de9cd)

Solutions

  1. Resolve once first: $db = $container->get('db'); after that getInstance('db') returns the cached instance
  2. Guard with $container->hasInstance('db') before calling
  3. If you just need the object, use get('db') — it builds and caches when the definition lifetime allows
  4. Check the definition lifetime — non-cached (factory) lifetimes may never populate the instance store

Example fix

// before
$db = $container->getInstance('db'); // InstanceNotFound

// after
$db = $container->hasInstance('db')
    ? $container->getInstance('db')
    : $container->get('db');
Defensive patterns

Strategy: validation

Validate before calling

$db = $container->hasInstance('db')
    ? $container->getInstance('db')
    : $container->get('db'); // builds and caches

Try / catch

use Phalcon\Container\Exceptions\InstanceNotFound;

try {
    $db = $container->getInstance('db');
} catch (InstanceNotFound $e) {
    $db = $container->get('db');
}

Prevention

When it happens

Trigger: Calling getInstance('db') before any get('db') has run; resolving via $container->$new('db') and then reading getInstance('db'); the definition using a factory lifetime that skips caching.

Common situations: Boot-order bugs where code reads a shared instance before first use; habits carried over from Phalcon\Di's getShared(); mixing fresh-resolution and cached-instance access patterns; tests that assume the container pre-populates instances.

Related errors


AI-assisted analysis of phalcon/cphalcon@b7419de9cd (2026-08-21). Data as JSON: /api/errors/2cb900a952fe6ef9. Report an issue: GitHub.