簡體   English   中英

如何將 Symfony HttpFoundation 與 PHP-DI 一起用於 MVC

[英]How to use Symfony HttpFoundation with PHP-DI for MVC

我正在努力為一個項目創建一個有效的 MVC 結構。

我正在使用什么:

這是我的代碼。

容器.php

$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->useAutowiring(true);
$containerBuilder->useAnnotations(true);
$containerBuilder->addDefinitions(__DIR__ . '/container-config.php');
$container = $containerBuilder->build();

容器配置.php

use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Psr\Container\ContainerInterface;

return [

    'request' => function() {
        return Symfony\Component\HttpFoundation\Request::createFromGlobals();
    },

    'session' => function() {
        return new Symfony\Component\HttpFoundation \Session\Session();
    }

    Environment::class => function () {

        $loader = new FilesystemLoader(__DIR__ . '/../templates');
        $twig = new Environment($loader, [
            'cache' => __DIR__ . '/../var/cache/templates',
        ]);

        return $twig;
    },
];

路由器.php

use Pecee\SimpleRouter\SimpleRouter as R;
use Pecee\Http\Middleware\BaseCsrfVerifier;
use App\App;

R::csrfVerifier(new BaseCsrfVerifier());
R::setDefaultNamespace('\App\Controller');
R::enableDependencyInjection($container);

R::get('/', 'ProductController@index', ['as' => 'products']);

R::start();

這是我的基地 controller

namespace App;

use Symfony\Component\HttpFoundation\Request;
use Twig\Environment;

class BaseController
{

    protected $request;

    protected $twig;

    public function __construct(Request $request, Environment $twig)
    {

        $this->request = $request;

        $this->twig = $twig;

    }

}

最后,我的產品controller

namespace App\Controller;

use App\BaseController;

class ProductController extends BaseController
{

    public function index()
    {

        dump($this->request); // returns the request object
        dump($this->request->query->all()); // return empty array

    }

}

第一個問題是我在容器上設置的請求 object 在我的 controller 中不起作用。

示例 url 示例.com example.com?foo=bar

dump($this->request)

此行應返回Symfony\Component\HttpFoundation\Request ,但它似乎是一個新行,因為我無法使用$this->request->query->all()獲取查詢參數,它返回空的。

如果我創建Symfony\Component\HttpFoundation\Request::createFromGlobals(); 作為一個全局變量,它按預期工作,並且轉儲$this->request->query->all()返回預期的數組。

所以我的問題是,我如何才能最好地將所有這些組件結合在一起以形成一個工作結構?

謝謝!

PHP-DI 中沒有任何內容表明依賴注入是根據參數名稱發生的,而是 class 是相關的。 PHP-DI 神奇地注入任何 class,如果它(尚未)定義 (如果沒有提供定義, AnnotationBasedAutowiring從無到有創建 class

但是,實際上使用注釋來觸發注入看起來非常不同,恕我直言顯然不是您想要的,或者您會這樣做。

由於您的定義只包含一個request條目,而不包含Symfony\Component\HttpFoundation\Request的條目,因此容器會很樂意為您創建一個條目。

要解決此問題,您必須設置一個不同的鍵,一個匹配的鍵:

use Symfony\Component\HttpFoundation\Request; // <-- added

return [
    Request::class => function() {
        return Request::createFromGlobals();
    },
    // ...
];

暫無
暫無

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

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