Reputation: 2048
I have a service in my Symfony app I know from the controller we can use it with the function $this->get('MyService');
but from a script outside of my controller how should I call it?
Upvotes: 1
Views: 86
Reputation: 52483
You have to register your outside-controller class as a service in your bundle's service configuration ( i'll assume yml configuration here )
services:
your_service_name:
class: Your/NonController/Class
arguments: ['@service_you_want_to_inject']
now in your class where you want to use the injected service:
// Your/NonController/Class.php
protected $myService;
// your 'service_you_want_to_inject' will be injected here automatically
public function __construct($my_service)
{
$this->myService = $my_service;
}
Remember for the Dependency Injection to happen you have to actually use this class as a service now - otherwise the injection will not happen automatically.
You can get your newly created service in a controller now as usual:
// 'service_you_want_to_inject' will be automatically injected in the constructor
$this->get('your_service_name');
There is also setter injection and property injection but that's out of this question's scope... Read more about DI in the Service Container chapter of the symfony documentation.
Upvotes: 1