Retrieve arguments in Service - Symfony - symfony

I want to understand service in symfony
I have read http://symfony.com/doc/2.3/book/service_container.html#creating-configuring-services-in-the-container
and I want to try to create my service
in my config.yml
services:
my_service:
class: Acme\FooBundle\myService
arguments: ['my_param']
in My controller
public function serviceAction(){
$Myservice = $this->get('my_service');
return array();
}
in My Class /service
class myService{
public function __construct() {
echo "In BaseClass constructor\n";
}
}
The Question is:
How can I Retrive my_param in my Class service?
I want to retrieve arguments: ['my_param']

Arguments are being passed to your service constructor as parameters:
class myService{
private $my_param;
public function __construct($param) {
$this->my_param = $param;
echo $this->my_param;
echo "In BaseClass constructor\n";
}
}

Related

How to get Symfony repository inside a class

I build validation system with Respect/Validation and I have validation rule for country name:
class CountryName extends AllOf
{
public function __construct()
{
parent::__construct(
new StringType(),
new NotEmpty(),
new Alpha(),
new Length(1, 100),
new CountryNameUnique()
);
}
}
Inside CountryNameUnique I have to check name in database. Structure of class is simple:
class CountryNameUnique extends AbstractRule
{
public function validate($input)
{
// validation here
return false;
}
}
But I have no idea how to get repository inside of CountryNameUnique. My services.yml
App\Domain\Country\Infrastructure\Repository\CountryRepository:
public: true
class: App\Domain\Country\Infrastructure\Repository\CountryRepository
factory: ["#doctrine.orm.default_entity_manager", getRepository]
arguments: [App\Domain\Country\Entity\Country]
I would very appreciate if somebody give me a right direction how to solve my problem. Thank you in advance.
As for all services autowire is enabled by default, you can inject the repository service by getting the repository in constructor method.
class CountryNameUnique
{
private $countryRepository;
public function __construct(CountryRepository $countryRepository)
{
$this->countryRepository = $countryRepository;
}
// ...
}

Symfony2 "Fatal error: Call to a member function get() on a non-object in.." when call service in controller

I have 2 controllers that use a same service:
CONTROLLER 1
namespace MO\FrontendBundle\Controller;
use MO\FrontendBundle\Controller\SuperClass\MOSearchController;
use Symfony\Component\HttpFoundation\JsonResponse;
class ResultsController extends MOSearchController {
public function detailAction() {
$vm = $this->get("vehicles_manager"); // SERVICE IN QUESTION
$result = $vm->getVehicleDetail($idVehicle);
}
}
CONTROLLER 2
namespace MO\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MetatagsController extends Controller {
public function metatagsController() {
$vm = $this->get("vehicles_manager"); // SERVICE IN QUESTION
$result = $vm->getVehicleDetail($idVehicle);
}
}
The service is regularly declared in services.yml file:
services:
vehicles_manager:
class: MO\FrontendBundle\Service\VehiclesManager
arguments: [#logger, %vehicles_manager.endpoint%, %vehicles_manager.scope%, %vehicles_manager.consumer%, %form_values.manual_gear_code%]
tags:
- { name: monolog.logger, channel: solrws }
vehicles_memory:
class: MO\FrontendBundle\Service\VehiclesMemory
arguments: [#request_stack]
The problem is that while in the first controller there are no errors, in the second i get the error:
Fatal error: Call to a member function get() on a non-object in C:\Users\d.test\workspace\test\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php on line 274
Any ideas?
In your second controller you didn't suffix the method name with Action then, it is not really an end point.
your code for the second controller should be:
namespace MO\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MetatagsController extends Controller {
public function metatagsAction() {
$vm = $this->get("vehicles_manager"); // SERVICE IN QUESTION
$result = $vm->getVehicleDetail($idVehicle);
}
}

Symfony Factory class

I would like to use a ResultFactory class as a service in my Symfony 2 application:
My Result factory class will be responsible to create a BaseResult instance.
Depending on the type passed to the get factory method, the ResultFactory will create the right ResultObject.
Here's what could be the code:
class ResultFactory
{
protected $translator;
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
public function get($type, $param)
{
$instance = null;
switch ($type) {
case 'Type1':
$instance = new Type1Result($param);
break;
case 'Type2':
$instance = new Type2Result($param);
break;
}
return $instance;
}
}
My question is:
I would like to use a service in my ResultObject. How do i inject this service to my ResultObject?
Thanks!
You are not using your service inside a result object. your factory is generating the result object.
You can define your factory service in services.yml of your bundle as:
result.factory:
class: ResultFactory
arguments: ["#translator"]
And in your controller you can call the service:
$resultObject = $this->get('result_factory')->get($type, $param);
Also you have core example how to create factory service using symfony2 in [the docs].(http://symfony.com/doc/current/components/dependency_injection/factories.html)

symfony2 : Pass serivce to service (controller as service) through configuration

I am trying to pass my service, defined in other bundle to controller which is defined as a service but getting null in contractor.
I know we can do it by passing the service_container but need to know if I can pass only specific service to the controller.
If the name is unique, no problem here.
namespace Yourapp\OneBundle\Controller;
class OneController extends Controller
{
public function oneAction()
{
$otherControllerManager = $this->get('youappOtherbundle.the_manager');
}
}
EDIT : Okay, it seemed to me that you could extend controller even it was a controller as service.
Why don't just "transmit" your required services as usual ?
In your services.yml
OneController.controller.service:
class: Yourapp\OneBundle\Controller\OneController
arguments: ["#templating", "#router"]
In your Controller:
public function __construct(EngineInterface $templating, UrlGeneratorInterface $router)
{
$this->templating = $templating;
$this->router = $router;
}

Access parameter from the Command Class

I am adding a new command line.
I would like to have access to the value of a parameter (parameters.yml) in my Class.
I read that i should add this class as a service to have access to the parameter. So
//config.yml
imports:
- { resource: services.yml }
//services.yml
services:
less_css_compiler:
class: MyVendor\MyBundle\Command\ThemeCommand
arguments: [%less_compiler%]
//parameters.yml
parameters:
less_compiler: WinLess.exe
it is said that normaly the argument is in the constructor of the class but if I do this :
public function __construct($less_compiler) {
$this->less_compiler = $less_compiler;
}
I have a warning saying that the first argument is missing. In the Command mother class there is a name as then unique argument of the constructor but even though I write :
public function __construct($name, $less_compiler) {
}
It does not change anything..
Other possibility is to call the service inside my class :
$service = $this->getContainer()->get('less_css_compiler');
But how do I get the argument ?
Thank you
Simple way, let command extend ContainerAwareCommand
$this->getContainer()->getParameter('parameter_name');
or
You should create seperate service class
$service = $this->getContainer()->get('less_css_compiler');
//services.yml
services:
less_css_compiler:
class: MyVendor\MyBundle\Service\LessCompiler
arguments: [%less_compiler%]
In service class, create constructor like above you mentioned
public function __construct($less_compiler) {
$this->less_compiler = $less_compiler;
}
Call the service from command class.
Thats it.
Reason: You are making command class itself as service, bit command class contructor expects the command name as the first argument.
I had the same problem when using Symfony 4.4. This blog post explains it very well.
If you use autowire just update your code as below:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class MessageGenerator
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function someMethod()
{
$parameterValue = $this->params->get('parameter_name');
// ...
}
}

Resources