如何解决Symfony 4 无效服务“my.myform.service”
我是 Symfony 的新手。我尝试从我的一个课程中提供服务。 当我运行 bin/console cache:clear 我得到这个错误:
在 ResolveNamedArgumentsPass.php 第 66 行:
无效的服务“my.myform.service”:您是否忘记将“$”前缀添加到参数“container”?
这是我的代码:
config/services.yaml:
my.myform.service:
class: App\Controller\MyformController
arguments:
container: "@service_container"
src/Controller/MessageController.php:
namespace App\Controller;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use App\Controller\MyformController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class MessageController extends AbstractController
{
/**
* @Route("/message",name="message",methods="GET")
*/
public function index(Request $request): Response
{
//$myform = new MyformController();
//$myform->createMyform();
$this->get("my.myform.service")->createMyform();
...
src/Controller/MyformController.php:
namespace App\Controller;
use App\Entity\Myform;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class MyformController extends AbstractController
{
public function __construct($container )
{
$this->container = $container;
}
/* protected function get($service)
{
return $this->container->get($service);
}
*/
public function createMyform(): Response
{
// you can fetch the EntityManager via $this->getDoctrine()
怎么了? PS 我在 MyformController 中注释了函数 get() 因为我有一个错误: PHP 致命错误:App\Controller\MyformController::get($service) 的声明必须与 Symfony\Bundle\FrameworkBundle\Controller\AbstractController::get(string $id): object in /home/admin/web/alpin52 兼容.ru/public_html/miriada/myform/src/Controller/MyformController.php 第 51 行 谢谢。
解决方法
您为什么使用专用方法获取服务?使用依赖注入,框架让您将服务定义为您的操作方法的参数
public function index(Request $request,YourServiceClass $serviceClass): Response
{
//$myform = new MyformController();
//$myform->createMyform();
$serviceClass->doSomething();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。