Services and Dependency injection
Sense uses The Symfony Dependency Injection component in order to manage the services in your application.
You can read about Dependency Injection and this component in the Symfony Documentation.
Configuration
You can define services and parameters in the YAML format. For do this, is required to create a file named services.yml in your config directory.
Sense will load the service configuration in each plugin, in the order you have specified at the Sense initialization.
Creating a service
First, you need to create your service class:
class ServiceName
{
private $attribute;
function __construct($parameter)
{
$this->attribute = $parameter;
}
function doStuff()
{
}
}
Then, in the services.yml, you can define your services and parameters in the same way you do in a Symfony project
#services.yml
parameters:
app.parameter_name: Your parameter here
services:
app.service_name:
class: Simettric\Plugin\ServiceName
arguments: ["%sense.parameter_name%"]
Using a service
In your controller then you can access to this service in this way
class MyAppController
{
/**
* @Route("/demo/{name}", name="profile")
*/
function profileAction($name)
{
$this->get("app.service_name")->doStuff();
//get a parameter
$param = $this->getParameter("app.parameter_name");
}
}
You can access to the container outside of the controller in this way too
$container = \Simettric\Sense\Kernel::getInstance()->getContainer();
$container->get("service_name");