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

Change already defined service

Hello,

I'd like to change a shared service on the fly, after being already resolved.

For eg:

$user1 = User::findFirstById(1);
$this->getDI()->setShared('user', $user1);
var_dump($this->getDI()->has('user')); // true
var_dump($this->user->getId()); // 1
$this->getDI()->remove('user');
var_dump($this->getDI()->has('user')); // false
$user2 = User::findFirstById(2);
$this->getDI()->setShared('user', $user2);
var_dump($this->getDI()->has('user')); // true
var_dump($this->user->getId()); // 1 !!!

As you can see, even though removing and setting a new definition, it still returns the id of the first set user.

Any help/advice is appreciated!

EDIT: Since then I've tried setRaw("user", new Service("user", $user2, true)) to no avail

Use better complex registration https://docs.phalcon.io/en/latest/reference/di.html#complex-registration

<?php

// Change the service class name
$di->getService("logger")->setClassName("MyCustomLogger");

// Change the first parameter without instantiating the logger
$di->getService("logger")->setParameter(
    0,
    [
        "type"  => "parameter",
        "value" => "../apps/logs/error.log",
    ]
);


145.0k
Accepted
answer
edited Sep '16

What is $this ? If it's class extending Injectable(like controller) then you need to do unset($this->user) too.

edited Sep '16

Thank you @Jurigag that was exactly the problem.

I guess this means that if i use this (user) service in another component, it has to be unset there too before access...

https://github.com/phalcon/cphalcon/blob/master/phalcon/di/injectable.zep#L136

This is what's going on here. You can just access user directly from di, not using magic property.

Yes, that occured to me too :]

for reference:

// change user service as before
$correctId = $this-getDI()->get('user')->getId();