Background
I have a OptionHelper
-Class that is looking in the database-table, where I store some flexible parameters. This class is working fine in Controllers.
Now I want to use this class in a function of another Service, but it explodes with the below mentioned error message.
OptionHelper.php
JavaScript
x
namespace AppService;
use AppEntityOptions;
use DoctrineORMEntityManagerInterface;
class OptionHelper {
private $emi;
public function __construct(EntityManagerInterface $emi) {
$this->emi = $emi;
}
public function get(string $optionName) {
$repository = $this->emi->getRepository(Options::class);
$options = $repository->findOneBy([ 'optionname' => $optionName ]);
$value = $options->getOptionvalue();
return $value;
}
}
CartItem.php
JavaScript
namespace AppService
class CartItem {
[ ]
public function __construct($name, $number, $id) {
$this->name = $name;
$this->number = $number;
$this->id = $id;
}
[ ]
private function getPrice(OptionHelper $optionHelper) { //<-- ERROR in this line
$price = $optionHelper->get('price');
return $price;
}
}
Controller
JavaScript
[ ]
public function addItem($name, $number, $id) {
$cartItem = new CartItem($name, $number, $id);
}
Error-Msg
JavaScript
Too few arguments to function AppServiceCartItem::getPrice(), 0 passed in /src/Service/CartItem.php on line 89 and exactly 1 expected
Question
Why isn’t it working in another Service? I tried also to put it into the constructor of CartItem
-Class, but doesn’t work too.
Do I have to add something in services.yaml
? But I have no idea, how to do it.
Thanks in advance for any help!
Advertisement
Answer
After a while I found the problem. It seems that you should never do this, because it disables the autowiring functionality.
- use
new ClassName($x, $y)
to create a new instance - only use autowirable Services in the constructor of a class
wrong
JavaScript
public function __construct($name, $number, $id) {
$this->name = $name;
$this->number = $number;
$this->id = $id;
}
JavaScript
public function addItem($name, $number, $id) {
$cartItem = new CartItem($name, $number, $id);
}
correct
JavaScript
public function __construct(OnlyServices $onlyServices) {
[ ]
}
public function create($name, $number, $id) {
$this->name = $name;
$this->number = $number;
$this->id = $id;
}
JavaScript
public function addItem($name, $number, $id, CartItem $cartItem) {
$cartItem->create($name, $number, $id);
}