簡體   English   中英

symfony中的構造函數注入

[英]constructor injection in symfony

我想在構造函數中使用Request類,這是在我想運行服務器時給我的錯誤:

無法自動裝配服務“ AppBundle \\ Controller \\ DetectServiceDetailController”:方法“ __construct()”的參數“ $ request”引用類“ Symfony \\ Component \\ HttpFoundation \\ Request”,但不存在這樣的服務。 由於它來自其他根名稱空間,因此無法自動注冊。

我的代碼:

<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

class DetectServiceDetailController
{
    public $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $serviceType = $this->request->query->get('type');
        return $serviceType;

    }

}

根據gp_sflover的建議,這是我在Symfony 3.4中使用的一段代碼:

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RequestStack;

class BaseController extends Controller
{
    protected $request;

    /**
     * @param Symfony\Bundle\FrameworkBundle\Controller\Controller
     */
    public function __construct(RequestStack $requestStack)
    {
        $this->request = $requestStack->getCurrentRequest();
    }

    ...

在我的案例中,BaseController擴展了Controller,因此我不需要更新services.yml,但是如果這是獨立的服務,則需要將其添加到services.yml中,例如

services:
    ...
    service_name:
        class: AppBundle\Service\ServiceName
        arguments:
            - '@request_stack'
        public: true

只是為經驗不足的開發人員添加它;-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM