If you have a habit of using an ORM inspired by the "active record" design pattern and you have switched to Symfony 3, you will be surprised that you cannot use a service (the logger for example) in an entity.
Indeed, nothing can be found other than the attributes and the business layer in the Symfony 3 entities.
In order to be able to use a service and to avoid having to repeat each action of the controller, you have to create a service (in which one has access to the other services).
To begin, you must define this service in the services.yml file located in the app/config directory:
services:
submission_file_saver:
class: AppBundle\Service\SubmissionFileSaver
arguments: ["@logger"]
Here we declare the service "SubmissionFileSaver" and we want to inject the service "logger".
We create our class "SubmissionFileSaver" and this one will have the following constructor:
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
We add one or more methods that will use this logger:
public function saveFiles($submission, $prefix = null) {
try {
//save file with $submission data
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage());
}
}
We can now inject and use this service in our actions of our controller:
public function registerAction(Request $request, SubmissionFileSaver $file_saver)
{
$submission = new Submission();
...$file_saver->saveFiles($submission, $prefix);
...
}