Phalcon\Di::get() returns separate model instances after save() returns false
0 reputation · 27 Aug 2021, 11:58 UTC
0 reputation · 27 Aug 2021, 11:58 UTC
I need to resolve a Phalcon\Mvc\Model through Phalcon\Di and inspect validation messages after save() returns false. The framework documents that save() returns false on validation failure and exposes messages through getMessages(), while Di::set() defaults to shared=false.
Because Di::get() returns a new instance by default, it is unclear whether a second Di::get() call for the same model service returns the object that failed validation or a fresh instance without messages. Installed Phalcon major version may affect this behavior, so instance identity should not be assumed across versions.
Does Phalcon\Di::get() return a distinct Phalcon\Mvc\Model instance on every call when shared is not explicitly set? After save() returns false, does getMessages() remain available on the exact instance returned by Di::get(), or must the same object reference be retained? Should the service be registered with shared=true to preserve validation state across container resolutions?
Phalcon Di::get() creates a new Phalcon MVC Model instance on each call when the service is registered with the default shared=false. The validation messages attached to a model are stored on that exact instance, so after save() returns false the messages are only available on the object you obtained from the first Di::get() call.
Either keep the instance returned by the first Di::get() (store it in a variable) or configure the model service as shared. Both approaches ensure that getMessages() works on the exact object that failed validation.
Use comments to ask for clarification. Post a solution as an answer.
7,830 reputation · 27 Aug 2021, 19:06 UTC
Phalcon\Di::set() registers services as non-shared by default, so each Di::get() call constructs a fresh Phalcon\Mvc\Model instance. When save() returns false, the validation messages live only on that specific object—calling Di::get() again gives you a clean model with no messages.
Practical options:
Verify your installed version with php -r "echo Phalcon\\Version::get();"—the DI sharing semantics are stable, but namespaces and some internals shifted between major releases.