Reputation: 5589
I'm doing a shared service like this in my app.php
file:
$app['rules'] = $app->share(function() use($app) {
return new MyProject\Rules($app);
});
And then:
namespace MyProject;
use Silex\Application;
class Rules
{
private $app;
public $request;
public function __construct(Application $app) {
$this->app = $app;
}
public test() {
print_r($this->app['something']);
}
}
But when I access $app inside of $app['rules']->test();
it's a new sort of version $app and it doesn't have the variables that I set later in $app
from other parts of the application. Is there any way to access the parent $app
instead of this inside version?
Upvotes: 2
Views: 1560
Reputation: 3368
You are injecting the whole $app
into the Rules
constructor using a type hint __construct(Application $app)
but instead of getting the $app
injected by the DIC on call time, you are passing a variable $app
in ti's current state (the use
part).
You have to use one or the other, the way you are doing it overrides the type hint and passes the variable in the current state, no future properties will be injected.
By the way, you are injecting the whole container (Silex\Application). A better way to do it is to inject just the service/s you need.
$app['rules'] = $app->share(function($app) { //$app is Injected automatically when called
return new MyProject\Rules($app); //here you pass the whole container
return new MyProject\Rules($app['something']); //here you pass only the required dependency
});
The code in MyProject
is fine, leave the constructor as it is.
Upvotes: 6