symfony2 and run service automatically
i found the solution, it seems that we should use listeners into services.yml like:
parameters: nevec_raxcido.core: Nevec\RaxcidoBundle\Model\Baseservices: nevec_raxcido.example: class: %nevec_raxcido.core% arguments: [@service_container] tags: - {name: kernel.event_listener, event: kernel.request, method: onKernelRequest}
and this model:
<?phpnamespace Nevec\RaxcidoBundle\Model;class Base{ public static $container; public function __construct($container) { self::$container = $container; } public function onKernelRequest($event){ return; }}
so you can access to the container in all scopes of your application with this:
$container = Model\Base::$container;
Please don't use the service container. Use dependency injection.
class Service { private $service; public function __construct(SomeServiceInterface $someService){ $this -> service = $service; }}
and the yml:
services: service1: class: SOMENAMESPACE\Service arguments: [@service2] service2: class: SOMENAMESPACE\SomeService
Now you can access SOMENAMESPACE\SomeService in SOMENAMESPACE\Service. And you can get the service in a controller via:
$this -> get('service1');
Let's say doctrine is your concrete service you want to inject.
Do this:
class Service { private $em; protected function getEm(ObjectManager $em){ $this -> em = $em; }}services: service1: class: SOMENAMESPACE\Service arguments: [@doctrine.orm.entity_manager]
Second part of the question: How to autoload? Pretty easy. Build a "BaseController" and extend it.
class BaseAppController extends Controller{ private $service; protected function getService(){ if (!($this -> service instanceof SomeServiceInterface)) $this -> service = $this -> get('service'); return $this -> service; }}
access via $this -> getService()