简体   繁体   English

通过 Symfony 中的路由在方法调用之前立即调用另一个方法

[英]Call another method immediately before the method call via route in Symfony

I'm very new to Symfony framework and I'm trying to replicate what I usually do with other languages (still following the MVC pattern)我对 Symfony 框架非常陌生,我正在尝试复制我通常用其他语言做的事情(仍然遵循 MVC 模式)

The target is to call InitializeSomething() everytime Fly() is called, immediately before.目标是在每次调用 Fly() 时立即调用 InitializeSomething()。 Here is my code:这是我的代码:

<?php
// src/Controller/ExampleController.php
namespace App\Controller;

use App\Common\Utils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class ExampleController extends BaseController
{
    public function __construct()
    {
      // Initialize vars and so on...
    }

    /**
     * @Route("/example/fly")
     */
    public function Fly()
    {
      // This method is obviously called via the route
    }

    private function InitializeSomething()
    {
      // I would like to call this before Fly() is executed
    }
...

of course the easiest way to reach the result is doing this:当然,达到结果的最简单方法是这样做:

...
    /**
     * @Route("/example/fly")
     */
    public function Fly()
    {
      $this->InitializeSomething();
      ...
    }
...

If there is no other elegant way to do that I will go for that solution, I just would like to avoid to spread all around my code the same method everywhere (the final home for the InitializeSomething method will be in the base class).如果没有其他优雅的方法可以做到这一点,我将为该解决方案提供 go,我只是想避免在我的代码中到处传播相同的方法(InitializeSomething 方法的最终归宿将在基类中)。

Usually with other languages I just call my InitializeSomething inside the constructor, because controller classes are instantiated every time a method is called, but here seems Symfony works in a different way and when constructor is called is too early to make my initialization.通常使用其他语言,我只是在构造函数中调用我的 InitializeSomething,因为每次调用方法时都会实例化 controller 类,但这里似乎 Symfony 以不同的方式工作,调用构造函数时为时过早,无法进行初始化。

Edit: Thank you for your advices.编辑:感谢您的建议。 Here are few examples of what I'm going to do.以下是我将要做的几个例子。

    private function InitializeSomething()
    {
      // Add the connection to a local variable, just to have a shortcut and avoid boilerplate
      $this->dbconnection = $this->getEntityManager()->getConnection();
      $this->dbengine = $this->getDoctrine();

      // Engine start
      if($engine==false) {
        SwitchOnEngine();
      }

      if($engine->rpm < 1000) {
        WaitEngineStart();
      }

      // Other things like logging the event and so on

    }

The point is if I forget to initalize the things, something wrong will happen and I want to minimize the errors by letting the machine to intialize the things automatically, once for every class.关键是如果我忘记初始化这些东西,就会发生错误,我想通过让机器自动初始化这些东西来最小化错误,每个 class 一次。

Symfony has what we call Events. Symfony 有我们所说的事件。 You can check the documentation but this specific event here is called right before the contoller gets executed: https://symfony.com/doc/current/reference/events.html#kernel-controller-arguments您可以查看文档,但在执行控制器之前会调用此处的特定事件: https://symfony.com/doc/current/reference/events.html#kernel-controller-arguments

Here you have the full documentation about the Symfony events component so you can understand how to implement what you need: https://symfony.com/doc/current/event_dispatcher.html在这里你有关于 Symfony 事件组件的完整文档,这样你就可以了解如何实现你需要的东西: https://symfony.com/doc/current/event_dispatcher.ZFC35FDC70D5FC69D269883A822C7A3E

You would end up with something like:你最终会得到类似的东西:

class InitializerListener
{
    public function onKernelController(ControllerEvent $event)
    {
        [$controllerInstance, $actionName] = $this->getController();
        $controllerInstance->initializeSomething();
    }
}

And in your config:在您的配置中:

# config/services.yaml
services:
    App\EventListener\InitializerListener:
        tags:
            - { name: kernel.event_listener, event: kernel.controller }

PS.: If your controller has more than one action method, getController returns an array in the format exemplified in the code above. PS.:如果你的 controller 有多个动作方法, getController会返回一个数组,格式如上面代码所示。 See: https://symfony.com/doc/current/event_dispatcher/before_after_filters.html请参阅: https://symfony.com/doc/current/event_dispatcher/before_after_filters.html

Also, don't start your methods with uppercase letters in PHP: https://www.php-fig.org/psr/psr-12/另外,不要在 PHP 中以大写字母开头您的方法: https://www.php-fig.org/psr/psr-12/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM